Add new element before another element in array php

In PHP, you can add a new element before another element in an array using the array_splice() function. Here's an example:

$array = array('a', 'b', 'c', 'd');
$newElement = 'x';

array_splice($array, 1, 0, $newElement);

print_r($array);

This will output:

Array
(
    [0] => a
    [1] => x
    [2] => b
    [3] => c
    [4] => d
)

The array_splice() function takes four arguments:

By using 0 as the $length argument, we're effectively inserting the new element without removing any existing elements.

Alternatively, you can use the array_merge() function to create a new array with the new element inserted before the desired position:

$array = array('a', 'b', 'c', 'd');
$newElement = 'x';

$array = array_merge(array($newElement), array_slice($array, 0, 1), array_slice($array, 1));

print_r($array);

This will also output the same result as the previous example.