How to Push Both Value and Key into a PHP Array
In this short tutorial, we will demonstrate to you how to push both value and key into a PHP array in the fastest and simplest ways.
Below, you can find the methods that we recommend you to use.
The first method that we recommend you to use is arrayname.
Here is the code to use:
$arrayname[indexname] = $value;
Using the union Operator
The second method is using the union operator (+) for combining and keeping the keys of the added array. Here is a proper example:
$arr1 = ['foo' => 'bar']; $arr2 = ['baz' => 'bof']; $arr3 = $arr1 + $arr2; print_r($arr3); // prints: // array( // 'foo' => 'bar', // 'baz' => 'bof', // );
Another method is to use array_merge in the following way:
array_merge($_GET, [$rule => $rule]);
Describing PHP Arrays
An array is considered a specific variable, capable of storing more than a value at a time.
So, a PHP array can hold multiple values under a single name. It is possible to access them by referring to an index number.
For creating an array, the array() function is used.