W3docs

How to Push Both Value and Key into a PHP Array

In this short tutorial, you will find comprehensive solutions on 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.

Direct Assignment

The first method is direct assignment. Here is the code to use:

<?php
$arrayname['indexname'] = $value;
?>

Using the Union Operator

The second method is using the union operator <kbd class="highlighted">(+)</kbd> to combine arrays. Note that keys from the left array take precedence, and keys from the right array are only added if they are not already present. 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
$arr1 = ['foo' => 'bar'];
$arr2 = ['baz' => 'bof'];
$result = array_merge($arr1, $arr2);
print_r($result);
?>

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 <kbd class="highlighted">array()</kbd> function is used.