Q:

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

0

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');

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now