What are PHP Associative Arrays? If you’re familiar with other programming languages, an associative array is pretty much a dictionary. Instead of accessing the array by using an index value, you’ll access it by using a key. That key points to a value. Keys in PHP can be integers or strings. If you attempt to store a floating point number as a key, it will be cast to an integer. Boolean value true will be case to 1 and false will be cast to 0.
We can access a regular array with the index value of the element, but we have to use the assigned key value to access an associative array element.
Why would you want to use an associative array over a regular array? If we had an array like the one below, how would we know what some of the values represent. We see that 32 is an element inside the array, but what does 32 actually mean?
<?php$person = [
"Dino Cajic",
32,
"dinocajic@gmail.com",
42.5,
true
];?>
If we wanted to specify what each of those values meant, we could use strings as our keys and explicitly state what each of the elements represent.
<?php$person = [
"name" => "Dino Cajic",
"age" => 32,
"email" => "dinocajic@gmail.com",
"fav_decimal" => 42.5,
"is_awesome" => true,
"occupation" => "author",
"book_title" => "An Illustrative Introduction to Algorithms",
"blog_link" => "https://medium.com/@dinocajic"
];?>
When someone views the array now, it’s a lot easier to figure out exactly what each element represents.
How do we access an element by using the key? By using the key instead of the integer index like we’ve been doing with simple arrays. The integer index value, because it hasn’t been defined as a key, will throw an error.
<?phpecho $person["name"]; // displays: Dino Cajic
echo $person[0]; // Throws an error?>
If we wanted to use an integer as a key, we could, but we probably shouldn’t. To add a new element to the associative array, we use the array name, and between the appended brackets, we specify the key name. We’ll use an integer value this time.
<?php$person[100] = "Hey There";
echo $person[100]; // Displays Hey There?>
We can delete an element from an associative array by using the unset() function.
<?phpunset( $person[100] ); // removes the Hey There elementvar_dump($person); // shows everything except Hey There.?>
To modify an element, use the key where the value is located and assign a new value to it.
<?php$person["age"] = 33; // replaces 32 with 33?>
Now that we have an introduction to associative arrays, we can move on to multidimensional arrays. We’ll cover that in the next article.