Print each element from an associative array in PHP

This tutorial is basically about we can fetch and print each element in the associative array in PHP, to do this there are various ways but to make it easy to understand and easy to implement I’m going to cover the basic approach here so that learning for you will be very easy.

Associative array in PHP

Before the start, we need to know what an associative array is in PHP. An associative array in PHP is a collection of unique keys and values where each key is in association with particular values. Associative array is the abstract data type and is similar to a hashmap(key, value) pair or map.

So, to create an associative array in PHP we are using the array() function.

let’s see how we can make use of the associative array suppose for a student named student one we need to store subject name and marks and this can’t be done using an indexed array so we need to create the unique key (subject name) and marks associated as values with each subject.

Implementing associative array in PHP

In PHP two ways to create an associative array.

$marks = array("Maths"=>"95", "Science"=>"97", "English"=>"83");

or

$marks ['Maths'] = "95";
$marks ['Science'] = "97";
$marks ['English'] = "83";

Now to traverse the associative array and print the content for each element. We can make use of the foreach() loop.

foreach($marks  as $x => $x_value) {
  echo "Key=" . $x . ", Value=" . $x_value;
  echo "<br>";
}

Sample code:

<!DOCTYPE html>
<html>
<body>

<?php
$marks = array("Maths"=>"95", "Science"=>"97", "English"=>"83");
foreach ($marks as $subject => $marks){ 
    echo "Student one got ".$marks." in ".$subject."\n"; 
}
?>

</body>
</html>

Output:

Student one got 95 in Maths 
Student one got 97 in Science 
Student one got 83 in English

 

Hope you like this tutorial. Do share with your friends.

Also Read: How To Get Yesterday’s Date in PHP|How to get the array key for a given value in PHP?

Leave a Reply

Your email address will not be published.