SEN 102 Computer Programming I - Week 2
SEN 102 Computer Programming I - Week 2
be used as arguments to the for array('name' => 'Kalle', 'salt' => 856412),
loops, the cost of evaluating this array('name' => 'Pierre', 'salt' => 215863)
expressions should not be );
expensive $size = count($people);
for($i = 0, $i < $size; ++$i) {
Wrong way:
$people[$i]['salt'] = mt_rand(000000, 999999);
$people = array(
}
array('name' => 'Kalle', 'salt' => 856412),
array('name' => 'Pierre', 'salt' => 215863)
);
for($i = 0, $size = count($people); $i < $size; ++$i) {
$people[$i]['salt'] = mt_rand(000000, 999999);
}
Foreach Loops
The foreach construct provides an easy way to iterate over arrays.
foreach works only on arrays and objects, and will issue an error when
you try to use it on a variable with a different data type or an
uninitialized variable.
There are two syntaxes:
foreach (iterable_expression as $value){
statement
}
foreach (iterable_expression as $key => $value){
statement
}
Foreach Loops Cont’d
Unsetting A Variable:
Example
$arr = array(1, 2, 3, 4);
$arr = array(1, 2, 3, 4);
foreach ($arr as $key => $value) {
foreach ($arr as $key =>
echo "{$key} => {$value}, "; $value) {
} echo "{$key} => {$value}, ";
Note: that the variable $value has its last value
retained even after exiting the foreach loop.
}
This can become a problem when passing that unset($value);
argument by reference as any modification to the
variable leads to modifications in the array. echo $value;
Solution is to unset the variable $value after exiting
the foreach loop
Foreach Loops Cont’d $array = [
Unpacking Nested Arrays With list() [1, 2],
It is possible to iterate over an [3, 4],
array of arrays and unpack the ];
nested array into loop variables foreach ($array as list($a, $b)) {
by providing a list() as the value. // $a contains the first element of the nested array,
For example: // and $b contains the second element.