In PHP, arrays are one of the most commonly used data structures that allow you to store multiple values in a single variable. You can create an array with numeric keys (indexed array) or with string keys (associative array).
In this blog post, we will discuss how to add a key-value pair to an array in PHP.
Adding Key-Value Pair to an Associative Array
To add a key-value pair to an associative array, you can simply use the assignment operator (=) and specify the key in square brackets []:
<?php
$associative_array = array(
"first_name" => "John",
"last_name" => "Doe"
);
$associative_array["age"] = 30;
print_r($associative_array);
?>
This will output the following array:
Array
(
[first_name] => John
[last_name] => Doe
[age] => 30
)
Adding Key-Value Pair to an Indexed Array
To add a value to an indexed array, you can simply use the array_push() function which will append the value to the end of the array:
<?php $indexed_array = array(10, 20, 30); array_push($indexed_array, 40); print_r($indexed_array); ?>
This will output the following array:
Array
(
[0] => 10
[1] => 20
[2] => 30
[3] => 40
)
Alternatively, you can use the empty square brackets [] without specifying the key to add a value to an indexed array:
<?php $indexed_array = array(10, 20, 30); $indexed_array[] = 40; print_r($indexed_array); ?>
The result will be the same as with the array_push() function:
Array
(
[0] => 10
[1] => 20
[2] => 30
[3] => 40
)
Conclusion
In this blog post, we learned how to add a key-value pair in both associative and indexed arrays in PHP. With these techniques, you can easily manage and manipulate arrays in your PHP applications.