25.09.2014 Views

ZEND PHP 5 Certification STUDY GUIDE

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

58 ” Arrays<br />

If, however, all you need to do is iterate through the entire array from start to finish,<br />

<strong>PHP</strong> provides a handy shortcut in the form of the foreach() construct:<br />

$array = array(’foo’, ’bar’, ’baz’);<br />

foreach ($array as $key => $value) {<br />

echo "$key: $value";<br />

}<br />

The process that takes place here is rather simple, but has a few important gotchas.<br />

First of all, foreach operates on a copy of the array itself; this means that changes<br />

made to the array inside the loop are not reflected in the iteration—for example,<br />

removing an item from the array after the loop has begun will not cause foreach to<br />

skip over that element. The array pointer is also always reset to the beginning of the<br />

array prior to the beginning to the loop, so that you cannot manipulate it in such a<br />

way to cause foreach to start from a position other than the first element of the array.<br />

<strong>PHP</strong> 5 also introduces the possibility of modifying the contents of the array directly<br />

by assigning the value of each element to the iterated variable by reference rather<br />

than by value:<br />

$a = array (1, 2, 3);<br />

foreach ($a as $k => &$v) {<br />

$v += 1;<br />

}<br />

var_dump ($a); // $a will contain (2, 3, 4)<br />

While this technique can be useful, it is so fraught with peril as to be something best<br />

left alone. Consider this code, for example:<br />

Licensed to 482634 - Amber Barrow (itsadmin@deakin.edu.au)<br />

$a = array (’zero’,’one’,’two’);<br />

foreach ($a as &$v) {<br />

}<br />

foreach ($a as $v) {<br />

}

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!