The array used in PHP is a very commonly used data structure that can store multiple elements of different types and access them using corresponding keys. Sometimes we need to add keys to the array to make it easier to operate on the array. This article will introduce how to add keys to arrays in PHP.
When we declare an array, we can add key-value pairs directly to it.
The sample code is as follows:
$fruits = array( "apple" => "red", "banana" => "yellow", "orange" => "orange" );
In the above sample code, we assigned a color to each fruit. Using this method, we can easily add keys to elements in the array.
In addition to adding keys directly when declaring the array, we can also use the [] operator to dynamically add keys.
The sample code is as follows:
$fruits = array(); $fruits["apple"] = "red"; $fruits["banana"] = "yellow"; $fruits["orange"] = "orange";
In the above sample code, we first created an empty array $fruits. Then, use the [] operator to add color to each fruit.
If we want to add elements at the end of the array and specify the key, we can use the array_push() function.
The sample code is as follows:
$fruits = array("apple", "banana", "orange"); array_push($fruits, "red apple", "green apple"); $fruits["red apple"] = "red"; $fruits["green apple"] = "green";
In the above sample code, we first create an array containing 3 elements. Then, using the array_push() function, two elements are added to the end of the array with the values "red apple" and "green apple". Then, I added color to both elements using the [] operator.
If we already have an array and want to add a key to each element, we can use a foreach loop.
The sample code is as follows:
$fruits = array("apple", "banana", "orange"); foreach ($fruits as $fruit) { $fruits_new[$fruit] = $fruit." color"; }
In the above sample code, we first create an array containing 3 elements. Then, a foreach loop is used to add a key to each element and the new array is assigned to $fruits_new.
Summary
This article introduces four methods of adding keys to arrays in PHP, including directly declaring key-value pairs, using the [] operator, using the array_push() function and using foreach cycle. Either way, you can easily add keys to the elements in the array to make it easier to operate on the array.
The above is the detailed content of How to add key to array in php. For more information, please follow other related articles on the PHP Chinese website!