Accessing All Elements of Numerical Arrays


 array('I', 'II', 'III', 'IV'); 


Looping through numerical arrays can most easily be done using foreach because in each iteration of the loop, the current element in the array is automatically written in a variable.

Looping Through an Array with foreach (foreach-n.php)
 <?php   $a = array('I', 'II', 'III', 'IV');   foreach ($a as $element) {     echo htmlspecialchars($element) . '<br />';   } ?> 

Alternatively, a for loop can also be used. The first array element has the index 0; the number of array indices can be retrieved using the count() function.

Looping Through an Array with for (for-n.php)
 <?php   $a = array('I', 'II', 'III', 'IV');   for ($i = 0; $i < count($a); $i++) {     echo htmlspecialchars($a[$i]) . '<br />';   } ?> 

Both ways are equally good (or bad); though, usually, using foreach is the much more convenient way. However, there is a third possibility: The PHP function each() returns the current element in an array. The return value of each() is an array, in which you can access the value using the numerical index 1, or the string index 'value'. Using a while loop, the whole array can be traversed. The following code once again prints all elements in the array, this time using each().

Looping Through an Array with each() (each-n.php)
 <?php   $a = array('I', 'II', 'III', 'IV');   while ($element = each($a)) {     echo htmlspecialchars($element['value']) .        '<br />'; //or: $element[1]   } ?> 

The output of the three listings is always the same, of course.




PHP Phrasebook
PHP Phrasebook
ISBN: 0672328178
EAN: 2147483647
Year: 2005
Pages: 193

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net