How to Array Push a Value with a Key in PHP?

In PHP, arrays are a fundamental data structure used for storing and manipulating collections of data.

While the array_push() function is commonly used to add elements to the end of a numeric-indexed (indexed) array, you may encounter situations where you need to add values with associated keys to an associative array.

This article will explain how to array push a value with a key in PHP and explore alternative methods to achieve this.

Understanding Associative Arrays

In PHP, an associative array is a type of array where each element is associated with a unique key, instead of being indexed numerically.

These keys can be strings, integers, or other data types, and they are used to access the corresponding values.

Unlike numeric-indexed arrays, associative arrays allow you to define custom keys.

Here's an example of an associative array:

$person = [
    "first_name" => "John",
    "last_name" => "Doe",
    "age" => 30
];

In this example, "first_name", "last_name", and "age" are keys, and "John", "Doe", and 30 are their respective values.


1. Using Square Brackets [] to Add Key-Value Pairs in PHP Array

To add key-value pairs to an associative array in PHP, you can use square brackets [] along with the assignment operator =.

Here's an example:

$person = [];
$person["first_name"] = "John";
$person["last_name"] = "Doe";
$person["age"] = 30;

print_r($person);

Output:

Array
(
    [first_name] => John
    [last_name] => Doe  
    [age] => 30
)

In this example, we start with an empty associative array $person and then use square brackets to assign values to specific keys.


2. Using the += Operator

The += operator allows you to combine an existing associative array with a new key-value pair, effectively adding it to the array.

Here's an example:

$person = [];
$person += ["first_name" => "John"];
$person += ["last_name" => "Doe"];
$person += ["age" => 30];

print_r($person);

Output:

Array
(
    [first_name] => John
    [last_name] => Doe  
    [age] => 30
)

In this example, each use of the += operator combines the existing array $person with a new key-value pair.

Conclusion

In PHP, associative arrays allow you to work with key-value pairs, providing flexibility and organization for your data.

While array_push() is designed for numeric-indexed arrays, adding key-value pairs to an associative array is typically done using square brackets [], the += operator.

These methods allow you to add values with associated keys to an associative array efficiently, ensuring that your data remains structured and accessible in your PHP code.