CodesJava

Easy learning with example program codes

PHP Associative Array


PHP Associative arrays are the arrays with named keys, that means named keys assigned to the elements of an array are used to access the elements of the array.

Syntax 1:

$arrayName = array(key1=>value 1, key2=>value 2, ...);

Syntax 2:

$arrayName[key1] = "value 1";
$arrayName[key2] = "value 2";
$arrayName[key3] = "value 3";

Example 1: Accessing the element of an Associative array.

<!DOCTYPE html>
<html>
<body>
 
<?php
$height = array("Jai"=>"5", "Rakesh"=>"7", "Joe"=>"4");
echo "Jai height is " . $height['Jai'] . " feet.";
?>
 
</body>
</html>

Output

Jai height is 5 feet.

Example 2: Looping through the elements of an Associative array.

<!DOCTYPE html>
<html>
<body>
 
<?php
$height = array("JAI"=>"5", "RAKESH"=>"6", "JOHNSON"=>"5");
 
foreach($height as $x => $x_value) {
	echo "Name = " . $x . ", Height (in feet) = " . $x_value;
	echo "<br>";
}
?>
 
</body>
</html>

Output

Name = JAI, Height (in feet) = 5
Name = RAKESH, Height (in feet) = 6
Name = JOHNSON, Height (in feet) = 5
Posted in PHP   
Sign Up/ Sign In
Ask a Question


Copyright © 2018 CodesJava DMCA.com Protection Status SiteMap Reference: Java Wiki