Different Ways To Insert Value In PHP Array

Different Ways To Insert Value In PHP Array

In this tutorial, you will learn different ways to insert value in PHP array with code examples.

1. Insert Values at the End of PHP Array

The PHP array_push() function is used to insert elements at the end of an array. This function takes two or more parameters –

  • array – The first parameter is an array.
  • $values – and after the array, you can pass multiple values as parameters to insert into the array.

Note: This function modifies the original array by appending new elements to the end.

array_push(array, $value1, $value2, $value3, ...);
<?php
$fruits = ["Apple", "Banana", "Watermelon"];

array_push($fruits, "Strawberry", "Pineapple");

print_r($fruits);
Array
(
    [0] => Apple
    [1] => Banana
    [2] => Watermelon
    [3] => Strawberry
    [4] => Pineapple
)

2. Insert Values at the Start of a PHP Array

array_unshift() function is used to add one or more elements to the beginning of an array. It modifies the original array by shifting existing elements to higher numeric keys to accommodate the new elements.

<?php
$fruits = ["Apple", "Banana", "Watermelon"];

array_unshift($fruits, "Strawberry", "Pineapple");

print_r($fruits);
Array
(
    [0] => Strawberry
    [1] => Pineapple
    [2] => Apple
    [3] => Banana
    [4] => Watermelon
)

3. PHP Array Insert Values with Keys

To insert values with keys into a PHP array, you can directly assign values to specific keys using the square bracket notation ([]). Here’s how you can do it:

$array = [];

// Insert values with keys
$array['key1'] = 'value1';
$array['key2'] = 'value2';
$array['key3'] = 'value3';

print_r($array);
Array
(
    [key1] => value1
    [key2] => value2
    [key3] => value3
)

4. Insert Value if the Value Not Exist in the Array

To insert a value into an array only if it doesn’t already exist in the array, you can use a conditional check (!in_array()) before adding the value. Here’s an example:

<?php
// Define an array of fruits
$fruits = ["Apple", "Banana", "Strawberry"];

/**
 * Inserts values into an array if they don't already exist.
 *
 * @param array $arr The array to insert values into.
 * @param mixed ...$values The values to insert.
 * @return void
 */
function array_insert_if_value_not_exist(&$arr, ...$values)
{
    // Iterate over each value to be inserted
    foreach ($values as $v) {
        // Check if the value already exists in the array
        if (!in_array($v, $arr)) {
            // Add the value to the array if it doesn't exist
            array_push($arr, $v);
        }
    }
}

// Call the function to insert values into the fruits array
array_insert_if_value_not_exist($fruits, "Pineapple", "Apple");

// Output the modified fruits array
print_r($fruits);
Array
(
    [0] => Apple
    [1] => Banana
    [2] => Strawberry
    [3] => Pineapple
)

5. Insert Value if the Key Not Exist in the Array

If you want to insert a value into an array only if the key doesn’t already exist, then check the key existence using array_key_exists() before inserting the value.

<?php
$array = [
    'key1' => 'value1',
    'key2' => 'value2'
];

$newKey = 'key2';
$newValue = 'new value';

// Check if the key already exists in the array
if (!array_key_exists($newKey, $array)) {
    // Add the value to the array with the specified key
    $array[$newKey] = $newValue;
    echo "Value inserted successfully.";
} else {
    echo "Key already exists in the array.";
}

print_r($array);
Key already exists in the array.Array
(
    [key1] => value1
    [key2] => value2
)

6. Insert Value in a Multidimensional Array in PHP

Here are the two ways to insert value in multidimensional array in PHP. Use one of the following two ways or methods the result will be same –

<?php
$data = [
    "fruits" => ["Apple", "Banana"],
    "vegetables" => ["Potato", "Tomato"]
];

array_push($data["fruits"], "Pineapple");
array_push($data["vegetables"], "Onion");

print_r($data);
<?php
$data = [
    "fruits" => ["Apple", "Banana"],
    "vegetables" => ["Potato", "Tomato"]
];

$data["fruits"][] = "Pineapple";
$data["vegetables"][] = "Onion";

print_r($data);
Array
(
    [fruits] => Array
        (
            [0] => Apple
            [1] => Banana
            [2] => Pineapple
        )

    [vegetables] => Array
        (
            [0] => Potato
            [1] => Tomato
            [2] => Onion
        )

)

Leave a Reply

Your email address will not be published. Required fields are marked *

We use cookies to ensure that we give you the best experience on our website. Privacy Policy