PHP loop through an associative array

Write a program to loop through an associative array using foreach() or with each().

Suppose an associative array is -

$a = array('One' => 'Cat', 'Two' => 'Dog', 'Three' =>'Elephant', 'Four' => 'fox');

Solution

In associative array, elements are defined in key/value pairs. 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.

<?php
$a = array('One' => 'Cat', 'Two' => 'Dog', 'Three' =>'Elephant', 'Four' => 'Fox');
foreach ($a as $key => $value)
{
   echo $key.' : '. $value.'<br/>';
}
?>

Output of the above code -

One : Cat
Two : Dog
Three : Elephant
Four : Fox

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'.

<?php
$a = array('One' => 'Cat', 'Two' => 'Dog', 'Three' =>'Elephant', 'Four' => 'Fox');
while ($element = each($a)) {
   echo htmlspecialchars($element['key'] . ': ' .$element['value']) . '<br/>';
}
?>

Output of the above code -

One : Cat
Two : Dog
Three : Elephant
Four : Fox




Related PHP Programs for Practice

PHP - Division table program
PHP - Prime Number Program
PHP - Print numbers 10 to 1 using recursion
PHP - Loop through an associative array
PHP - Differentiate between fgets, fgetss and fgetcsv
PHP - Set session on login
PHP - Convert text to speech
PHP - Copying or moving a file
PHP - Locking a file
PHP - CURL Cookie Jar
PHP - Password Hashing
PHP - Emoji Unicode Characters




Read more articles


General Knowledge



Learn Popular Language