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.

Using arrayname

The first method that we recommend you to use is arrayname.

Here is the code to use:

<?php

$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:

<?php

$arr1 = ['foo' => 'bar'];
$arr2 = ['baz' => 'bof'];
$arr3 = $arr1 + $arr2;
print_r($arr3);
// prints: // array( // 'foo' => 'bar', // 'baz' => 'bof', // );

?>

Using array_merge

Another method is to use array_merge in the following way:

<?php

array_merge($_GET, [$rule[0] => $rule[1]]);

?>

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.