![]() |
VOOZH | about |
An associative array in PHP is a special array where each item has a name or label instead of just a number. Usually, arrays use numbers to find things.
To create an associative array in PHP, we use the array() function or the short [] syntax, and assign keys to values using the => operator.
$array = array(
"key1" => "value1",
"key2" => "value2",
"key3" => "value3"
);Or using short syntax (PHP 5.4+):
$array = [
"key1" => "value1",
"key2" => "value2",
"key3" => "value3"
];Now, let us understand with the help of the example:
Anjali 23 New York
The easiest way to loop through an associative array is by using the foreach loop. It lets us access both the key and the value in each iteration.
Now, let us understand with the help of the example:
The color of apple is red. The color of banana is yellow. The color of grape is purple.
This way, each key ($fruit) and its corresponding value ($color) are available inside the loop.
If you want to use a for loop instead of foreach, you first need to get all the keys using array_keys(). Then you can loop through these keys and access their values.
Now, let us understand with the help of the example:
The color of apple is red. The color of banana is yellow. The color of grape is purple.
Before working with a key, it’s good to check if it exists to avoid errors. You can use array_key_exists() or isset() for this.
Now, let us understand with the help of the example:
Key 'x' is present in the array. Key 'z' does not exist.
To remove a key-value pair, use theunset() function with the key.
Now, let us understand with the help of the example:
Array ( [first] => one [third] => three )
PHP provides many built-in functions to work with arrays, including associative arrays. Some useful ones are:
Associative arrays are useful when:
Below is the following difference between the Indexed and Associative Arrays:
| Indexed Array | Associative Array |
|---|---|
| Uses numeric keys (0,1,2,…) | Uses named keys (strings) |
| Elements accessed by position | Elements accessed by key name |
Example:$colors = ["red", "blue", "green"]; | Example:$person = ["name" => "GFG", "age" => 30]; |
Associative Arrays in PHP let us store and access data using meaningful names instead of just numbers. This makes our code easier to read and work with, especially when dealing with related information like user details or product data. By using keys, we can quickly find, update, or remove items. PHP also gives us helpful functions to manage associative arrays smoothly. Overall, associative arrays are a handy way to organize data clearly without needing complex structures.