PHP Associative Array or String Indexed Example Code foreach Loop

PHP Associative Array

PHP Associative Array is also used to store more than one element and which is identified by the string. It also knowns as string indexed array.

Syntax Of Associative Array creation and accessing.

<!DOCTYPE html>
<html>
  <head>
   
  </head>
  
  <body>
	<?php
		 $arrayName = array("string" => "value of array");
         
        $arraName['string0'] = "value1"; 
        $arraName['string1'] = "value2";
        $arraName['string2'] = "value3";
        $arraName['string3'] = "value4";
	?>
  </body>
</html>

The above syntax are used to create an associative array. The above syntax have 2 different ways to create an associative array.

Example 1 – Associative Array Example code to store the marks of student

<!DOCTYPE html>
<html>
  <head>
   
  </head>
  
  <body>
	<?php
		 $marks = array("Maths" => "90", "Physics" => "65", "Chemistry" => "70");
         
        $arraName['Maths'] = "90"; 
        $arraName['Physics'] = "65";
        $arraName['Chemistry'] = "70";
        $arraName['Biology'] = "56";
	?>
  </body>
</html>			 

The above code shows how you can create an associative array. And this associative array are called by its string index.

Example 2 – Associative Array Example code to create and display its value.

<!DOCTYPE html>
<html>
  <head>
   
  </head>
  
  <body>
	<?php
		
		$marks = array("Maths" => "90", "Physics" => "65", "Chemistry" => "70");		
		echo "Maths Marks is " . $marks["Maths"] . "<br />" . "Physics Marks is " . $marks["Physics"] . "<br />" . "Chemistry Marks is " . $marks["Chemistry"]; 
	?>
  </body>
</html>			 

The above code shows how you can create an associative array. And this associative array are called by string.

PHP Associative Array Example code to create and display its value.
Fig.1 – Associative Array Example code to create and display its value with echo function.

PHP Array foreach Loop Example Code

The foreach is a looping statement and it is only applicable in an array. And it is used to loop through every element of an array.

Example 3 – PHP Associative Array with foreach loop Example

<!DOCTYPE html>
<html>
  <head>
   
  </head>
  
  <body>
	<?php
		
		$marks = array("Maths" => "90", "Physics" => "65", "Chemistry" => "70");		
		foreach ($marks as $key => $value)
		{
			echo $key . "-" . $value . "<br />";
		}
	?>
  </body>
</html>

The above example we used a foreach loop to print the value of $marks array with the name of subjects.

PHP Array foreach Loop Example Code with Associative
Fig.2 – Associative Array with foreach Loop example code.
You can leave a response, or trackback from your own site.
Leave a Reply to the article


Learn PHP

Learning & Certifications
Follow Us
Facebook Icon   Linked In Icon   Twitter Icon  
Validation and Recognition

Valid CSS! Valid HTML5!          Protected by Copyscape