• Post category:PHP

how to create an associative array in PHP

PHP Create an Associative Array

Learn how to create an associative array in PHP with example codes. As described earlier, an associative array assigns names to the positions in the array. This provides a user-friendly way to access array elements than the numerical key approach outlined above. Once again, the array() function is used to create the array, with optional arguments to pre-initialize the array elements.

Set a key for each value and link the two using the “=>” connector in order to assign all the values of such an array in a single statement> Remember to separate each key-value pair with commas. In the case of an associative array, the arguments are of the form key => value where the key is the name by which the element will be referenced, and the value is the value to be stored in that position in the array. We can assign a key name to each element in the array as follow:


$arrayname = array("key1" => value1, "key2" +> value2, ...);


$customer = array('name' => 'john', 'address' => '1st street, anna nagar' , 'accnum' => '1234');
echo $customer['name'];


$customer['name'] = 'John';
$customer['address'] = '1st street, anna nagar';
$customer['accnum'] = '1234';
echo $customer['address'];


php create associative array

Here, we have created an associative array and assigned a key to each element. We can use those names to access the corresponding array values. The one-dimensional associative arrays can be processed by foreach and array iterator loops. Therefore, extract the customer’s name and address from our $customer array variable.

Leave a Reply