Associative arrays in PHP are powerful data structures that allow you to store key-value pairs. This article covers everything you need to know about using associative arrays effectively.
Creating Associative Arrays
Associative arrays can be created using the array() constructor or the shorthand square bracket notation. Here are some examples:
<?php
// Using array() constructor
$person = array(
'name' => 'Edward Nyirenda Jr.',
'age' => 25,
'email' => 'edward@coderscratchpad.com'
);
// Using square bracket notation
$car = [
'make' => 'Chevrolet',
'model' => 'Camaro',
'year' => 1969
];
The code examples demonstrate two ways to create associative arrays in PHP: using the array() constructor and the shorthand square bracket notation. Associative arrays allow you to assign values to specific keys instead of relying on numeric indices.
Accessing Array Elements
You can access array elements using their keys. Here are a few ways to do it:
Using square brackets and the corresponding key:
<?php
// Using array() constructor
$person = array(
'name' => 'Edward Nyirenda Jr.',
'age' => 25,
'email' => 'edward@coderscratchpad.com'
);
// Using square bracket notation
$car = [
'make' => 'Chevrolet',
'model' => 'Camaro',
'year' => 1969
];
// Using square bracket notation
// Accessing the person name
$name = $person['name'];
// Accessing the car make
$make = $car['make'];
// Print the person name
echo "The person's name is $name. <br />";
// Print the car make
echo "The car make is $make. <br />";
Using the array_key_exists function to check if the key exists in the associative array:
<?php
// Using array() constructor
$person = array(
'name' => 'Edward Nyirenda Jr.',
'age' => 25,
'email' => 'edward@coderscratchpad.com'
);
// Using square bracket notation
$car = [
'make' => 'Chevrolet',
'model' => 'Camaro',
'year' => 1969
];
// Using array_key_exists()
if (array_key_exists('name', $person)) {
// Accessing the person name
$name = $person['name'];
// Print the person name
echo "The person's name is $name. <br />";
}
// Using array_key_exists()
if (array_key_exists('make', $car)) {
// Accessing the car make
$make = $car['make'];
// Print the car make
echo "The car make is $make. <br />";
}
Using the null coalescing operator (??), introduced in PHP 7+ to assign a default value if the specified key does not exist in the array:
<?php
// Using array() constructor
$person = array(
'name' => 'Edward Nyirenda Jr.',
'age' => 25,
'email' => 'edward@coderscratchpad.com'
);
// Using square bracket notation
$car = [
'make' => 'Chevrolet',
'model' => 'Camaro',
'year' => 1969
];
// Using null coalescing operator (PHP 7+)
// Accessing the person name, John Doe will be assigned to the
// variable name if the key 'name' does not exist on the person array
$name = $person['name'] ?? 'John Doe';
// Print the person name
echo "The person's name is $name. <br />";
// Accessing the car make, Toyota will be assigned to the
// variable make if the key 'make' does not exist on the car array
$make = $car['make'] ?? 'Toyota';
// Print the car make
echo "The car make is $make. <br />";
Modifying Array Elements
To modify values in associative arrays, you can directly assign new values, use the unset() function to remove elements, or utilize the array_replace() function. Here are examples:
Direct assignment
You can directly modify the value of an element by assigning a new value to its corresponding key:
<?php
// Using array() constructor
$person = array(
'name' => 'Edward Nyirenda Jr.',
'age' => 25,
'email' => 'edward@coderscratchpad.com'
);
// Direct assignment
$person['age'] = 28;
/* Output:
Array (
[name] => Edward Nyirenda Jr.
[age] => 28
[email] => edward@coderscratchpad.com
)
*/
print_r($person);
The unset() Function
The unset() function removes a specific element from the associative array by specifying its key:
<?php
// Using square bracket notation
$car = [
'make' => 'Chevrolet',
'model' => 'Camaro',
'year' => 1969
];
// Removing an element
unset($car['year']);
/* Output:
Array (
[make] => Chevrolet
[model] => Camaro
)
*/
print_r($car);
The array_replace Function
This function replaces the elements of an array with the elements of another array, ensuring that existing keys are preserved and new keys are added:
<?php
// Using square bracket notation
$car = [
'make' => 'Chevrolet',
'model' => 'Camaro',
'year' => 1969
];
// Replacing array elements
$newCar = array_replace($car, ['color' => 'Blue', 'year' => 2023]);
/* Output:
Array (
[make] => Chevrolet
[model] => Camaro
[year] => 2023
[color] => Blue
)
*/
print_r($newCar);
Adding and Removing Elements
Associative arrays offer methods for adding and removing elements. Here are a few examples:
Adding an Element
You can add a new key-value pair to an associative array by assigning a value to a new key:
<?php
// Using square bracket notation
$car = [
'make' => 'Chevrolet',
'model' => 'Camaro',
'year' => 1969
];
// Adding an element at the end
$car['price'] = 65000;
/* Output:
Array (
[make] => Chevrolet
[model] => Camaro
[year] => 1969
[price] => 65000
)
*/
print_r($car);
Removing an Element
The functions array_shift() and array_pop() remove the first and last elements of the array, respectively:
<?php
// Using array() constructor
$person = array(
'name' => 'Edward Nyirenda Jr.',
'age' => 25,
'email' => 'edward@coderscratchpad.com'
);
// Using square bracket notation
$car = [
'make' => 'Chevrolet',
'model' => 'Camaro',
'year' => 1969
];
// Removing the first element
array_shift($person);
/* Output:
Array (
[age] => 25
[email] => edward@coderscratchpad.com
)
*/
print_r($person);
// Removing the last element
array_pop($car);
/* Output:
Array (
[make] => Chevrolet
[model] => Camaro
)
*/
print_r($car);
Looping through Associative Arrays
You can iterate over associative arrays using the foreach loop construct. Here’s an example:
<?php
// Using array() constructor
$person = array(
'name' => 'Edward Nyirenda Jr.',
'age' => 25,
'email' => 'edward@coderscratchpad.com'
);
// Iterating over the person array
foreach ($person as $key => $value) {
echo "$key: $value <br />";
}
The foreach loop is commonly used to iterate over associative arrays. It assigns each key-value pair to temporary variables for easy access within the loop body.
Checking Array Keys and Values
You can check if keys or values exist in associative arrays using functions like array_key_exists(), in_array(), and array_search(). Here’s an example:
The array_key_exists() Function
This function checks if a specific key exists in the associative array:
<?php
// Using array() constructor
$person = array(
'name' => 'Edward Nyirenda Jr.',
'age' => 25,
'email' => 'edward@coderscratchpad.com'
);
if (array_key_exists('email', $person)) {
echo 'Email exists';
}
The in_array() Function
It checks if a given value exists within the array:
<?php
// Using square bracket notation
$car = [
'make' => 'Chevrolet',
'model' => 'Camaro',
'year' => 1969
];
if (in_array('Chevrolet', $car)) {
echo 'Chevrolet found';
}
The array_search() Function
This function searches for a value in an array and returns the corresponding key if found:
<?php
// Using array() constructor
$person = array(
'name' => 'Edward Nyirenda Jr.',
'age' => 25,
'email' => 'edward@coderscratchpad.com'
);
$key = array_search(25, $person);
echo "Key: $key";
Sorting Associative Arrays
Associative arrays can be sorted based on keys or values using functions like asort(), ksort(), arsort(), and krsort(). Here’s an example:
The asort() Function
This function sorts an associative array by its values in ascending order, maintaining the key-value relationship:
<?php
// Using square bracket notation
$car = [
'make' => 'Chevrolet',
'model' => 'Camaro',
'year' => 1969
];
asort($car);
/* Output:
Array (
[year] => 1969
[model] => Camaro
[make] => Chevrolet
)
*/
print_r($car);
The ksort() Function
It sorts an associative array by its keys in ascending order, rearranging the elements accordingly:
<?php
// Using square bracket notation
$car = [
'make' => 'Chevrolet',
'model' => 'Camaro',
'year' => 1969
];
ksort($car);
/* Output:
Array (
[make] => Chevrolet
[model] => Camaro
[year] => 1969
)
*/
print_r($car);
The arsort() Function
This function sorts an associative array by its values in descending order:
<?php
// Using square bracket notation
$car = [
'make' => 'Chevrolet',
'model' => 'Camaro',
'year' => 1969
];
arsort($car);
/* Output:
Array (
[make] => Chevrolet
[model] => Camaro
[year] => 1969
)
*/
print_r($car);
The krsort() Function
It sorts an associative array by its keys in descending order:
<?php
// Using square bracket notation
$car = [
'make' => 'Chevrolet',
'model' => 'Camaro',
'year' => 1969
];
krsort($car);
/* Output:
Array (
[year] => 1969
[model] => Camaro
[make] => Chevrolet
)
*/
print_r($car);
Conclusion
This article covered the fundamental aspects of associative arrays in PHP. With the provided code examples and explanations, you now have a solid understanding of how to create, access, modify, iterate, and manipulate associative arrays. Start leveraging the power of associative arrays to build dynamic and flexible PHP applications.
Sources:
I hope you found this information informative. If you would like to receive more content, please consider subscribing to our newsletter!