Search code examples
phpmanual

Since PHP 7.3 `array_unshift()` can be called with only one parameter. What's the point?


As it said in the PHP manual about array_unshift() function:

7.3.0 This function can now be called with only one parameter. Formerly, at least two parameters have been required.

I didn't get it. How to use such function with only one parameter?

I tried to guess, but nothing happens:

$arr = ['one' => 'test', 'two' => 'some'];
array_unshift($arr);
print_r($arr);

// Result:
// Array
// (
//    [one] => test
//    [two] => some
// )

$arr1 = ['what', 'ever'];
array_unshift($arr1);
print_r($arr1);

// Array
// (
//    [0] => what
//    [1] => ever
// )

The arrays haven't changed.

Does anyone know what exactly PHP contributors suggest?


Solution

  • I think my comment might need some more explanation, hopefully this makes it clearer.

    If I have two arrays, and I want to add all elements from the second to the end of the first, using array_push combined with the unpacking operator lets me do it like this:

    $a = [1, 2, 3];
    $b = [4, 5, 6];
    
    array_push($a, ...$b);
    

    $a is now [1, 2, 3, 4, 5, 6]

    (array_unshift lets me do the same, but add the elements to the beginning of the array instead. Using array_push I think makes the example clearer)

    Before PHP 7.3, if $b was empty then a warning would be raised, as unpacking an empty array is the equivalent of only passing the first argument. See the demo here: https://3v4l.org/GZQoo. $a would still be unchanged, which is the desired outcome, so it's just unnecessary noise in the logs.

    In a practical example, if $b was being generated by another function (calling a database, etc) then without this change I'd need to call if (!empty($b) ... before running the code to prevent the warning. Now, it works silently.

    Note: There are other ways of appending an array to another (array_merge, array_replace and the + operator), but they all have particular ways of merging and de-duplicating shared keys. This method simply appends all values of the second to the first, regardless of the keys.