Accessing All Elements of Associative Arrays


 foreach ($array as $key => $value) { 


When using an associative array and wanting to access all data in it, the keys are also of relevance. For this, the foreach loop must also provide a variable name for the element's key, not only for its value.

Looping Through an Associative Array with foreach (foreach-a.php)
 <?php   foreach ($array as $key => $value) = array('one'     => 'I', 'two' => 'II', 'three' => 'III', 'four'     => 'IV');   foreach ($array as $key => $value) {     echo htmlspecialchars("$key: $value") . '<br />';   } ?> 

Using count() is possible: count() returns the number of values in the array, not the number of elements. Looping through all array elements with for is not feasible. However, the combination of each() and while can be used, as can be seen in the following code. The important point is that the key name can be retrieved either using the index 0 or the string index 'key'.

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




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