In PHP, associative array is a very commonly used data type. It stores key-value pairs as units, and the corresponding values can be easily accessed through key names. During the development process, we often need to add or delete elements to associative arrays. So, this article will introduce how to add an item to an associative array in PHP.
Method to add an item to an associative array:
We can directly use subscript assignment, Add an item to an associative array. For example, the following code adds a key-value pair named age
to an associative array named $info
, where 18
is the value:
$info = array("name"=>"Tom","gender"=>"male"); $info["age"] = 18;
In the above code, we created an associative array named $info
and added a age
key-value pair to it, where $ The value of info["age"]
is 18
. If you want to add other key-value pairs, just do it the same way.
array_push
function We can also use PHP’s built-in array_push()
function to implement associative array The purpose of adding an item.
But please note that the array_push() function adds one or more elements to the end of the array instead of adding key-value pairs, so you need to find a way to convert the operation.
The implementation method is as follows:
$info = array("name"=>"Tom","gender"=>"male"); $age = array("age"=>18); $info = $info + $age;
In the above code, we first create an associative array named $info
. Then, we use the $age
array to store the age
key-value pairs. Finally, we use the plus operator to add the two arrays and reassign it to the $info
array, which is equivalent to adding an item $age to
$info
Array.
array_merge
function In addition to using the plus operator for addition, we can also use PHP's array_merge()
Function, merge two arrays into a new array.
The implementation method is as follows:
$info = array("name"=>"Tom","gender"=>"male"); $age = array("age"=>18); $info = array_merge($info,$_age);
In the above code, we first create an associative array named $info
. Then, we use the $age
array to store the age
key-value pairs. Finally, we use the array_merge()
function to merge the $info
and $age
arrays into a new array, which is equivalent to $info
An item was added to the $age
array.
Summary:
In PHP, adding an item to an associative array is a very simple operation. We can directly use subscript assignment to add key-value pairs to the associative array; we can also use the array_push()
function or the array_merge()
function to operate on the array. The above is the specific method of adding an item to an associative array.
The above is the detailed content of How to add an item to php associative array. For more information, please follow other related articles on the PHP Chinese website!