Foreach As Key Value Loop
From Sputnik Wiki
Contents |
Foreach As Key Value
Description
Loop based on an expression.
foreach( <expression> as <key> => <value> ) { statements ... } foreach( <expression> as <key> => <value> from <offset> ) { statements ... } foreach( <expression> as <key> => <value> from <start> to <end> ) { statements ... }
Parameters
expression
An expression needs to be an array for this loop to happen.
key
The variable to place the key in most common as a $variable.
value
The variable to place the value in most common as a $variable.
Remarks
Foreach...As..Key..Value statements may be nested.
Example
Here we cycle through binary data :
$var = array( "One" => 100, "Two" => 200, "Three" => 300 ); Foreach ($var as $key => $value) { println( "Key '$key' | Value '$value'" ); }
A reverse foreach
$var = array( "One" => 100, "Two" => 200, "Three" => 300 ); println( "Key '$key' | Value '$value'" ) Foreach ($var as $key => $value);
Using from
$var = array( "One" => 100, "Two" => 200, "Three" => 300, "Four" => 300 ); Foreach ($var as $key => $value from 1) { println( "Key '$key' | Value '$value'" ); }
Using from and to
$var = array( "One" => 100, "Two" => 200, "Three" => 300, "Four" => 300 ); Foreach ($var as $key => $value from 1 to 2) { println( "Key '$key' | Value '$value'" ); }