close[x]


PHP

PHP-Home PHP-Environment Setup PHP-Syntax PHP-Run PHP in XAMPP PHP-Variable PHP-Comment PHP-Datatype PHP-String PHP-Operators PHP-Decision PHP-loop PHP-Get/Post PHP-Do While loop PHP-While loop PHP-For loop PHP-Foreach loop PHP-Array PHP-Multidimensional Arrays PHP-Associative Arrays PHP-Indexed Arrays PHP-Function PHP-Cookies. PHP-Session PHP-File upload PHP-Email PHP-Data & Time PHP-Include & Require PHP-Error PHP-File I/O PHP-Read File PHP-Write File PHP-Append & Delete File PHP-Filter PHP-Form Validation PHP-MySQl PHP-XML PHP-AJAX



learncodehere.com




PHP - Associative Array

The associative arrays are very similar to numeric arrays in term of functionality.

Associative array will have their index as string so that you can establish a strong association between key and values.

There are two ways to create indexed arrays:

Syntax : Create Associative Array


 //index can be assigned automatically (index always starts at 0)
 $variable = array("string1"=>"value1", "string2"=>"value2",.... "string3"=>"valueN");
  
//the index can be assigned manually
$variable["string1"] = "value1";
$variable["string2"] = "value2";
$variable["string3"] = "value3";
.
.
$variable["stringN"] = "valueN";

Let's put these syntax into real use.

Following is the example showing how to create and access associative arrays.

Example : foreach Loop


<?php 
/* First method to associate create array. */
$age = array("sara" => 24, "kal" => 34, "will" => 15);
echo "age of sara is ". $age['sara'] . "<br />";
echo "age of kal is ".  $age['kal']. "<br />";
echo "age of will is ".  $age['will']. "<br />";
/* Second method to create array. */
$age['sara'] = 24;
$age['kal'] = 34;
$age['will'] = 15;
echo "age of sara is ". $age['sara'] . "<br />";
echo "age of kal is ".  $age['kal']. "<br />";
echo "age of will is ".  $age['will']. "<br />";
?>

This will produce the following result −

Result


age of sara is 24
age of kal is 34
age of zara is 15
age of sara is 24
age of kal is 34
age of zara is 15