1. php
  2. /references
  3. /associative-array

PHP Associative Arrays

A PHP associative array is an array that uses strings as its keys. An associative array can be created by enclosing a comma-separated list of key-value pairs in curly braces {}, or by using the array function.

Usage

Here's an example of creating an array using both methods:

// Bracketed associative array
$person = [
	'name' => 'John', 
	'age' => 30, 
	'gender' => 'male'
	];

// Using the array function
$person = array(
	'name' => 'John', 
	'age' => 30, 
	'gender' => 'male'
	);

Looping through an associative array

To loop through an associative array, you can use a foreach loop. Here's an example of how to loop through the $person array and print out each key and value:

foreach ($person as $key => $value) {
    echo "$key: $value\n";
}

This will output:

name: John
age: 30
gender: male

You can also use a for loop with the array_keys and array_values functions to loop through the keys and values of an associative array, like this:

for ($i = 0; $i < count(array_keys($person)); $i++) {
    echo array_keys($person)[$i] . ": " . array_values($person)[$i] . "\n";
}

This will output the same as the first method.

See also:

PHP Indexed Array

PHP Multidimensional Array