1

http://php.net/manual/en/function.array-push.php clearly shows the signature of the function with the variadic being completely optional:

int array_push ( array &$array [, mixed $... ] )

I think that, when using array_push with splat operator, it would be extremely desired for it to accept empty variadic, e.g. to allow such code:

<?php

function add( array $arr1, array $arr2 ) {
    return \array_push($arr1, ...$arr2);
}

echo add(['foo'], ['bar']); // OK, returns 2
echo add(['foo'], []); // should be OK, but ain't currently - raises an E_WARNING
?>

Many languages (e.g. Java) allow empty variadics in functions (usually resulting in a no-op) for that exact reason. PHP doesn't, at least not in PHP 7.1 nor 7.2.

OTOH, although sharing a similar syntax definition, array_merge and many other accept the empty variadic and work correctly using the aformentioned splat syntax:

var_dump( array_merge(['foo'], ...[]) ); // works for me.

My questions are:

  1. is this actually a intended behaviour and a documentation error, a bug in implementation, or something else?
  2. (a) if this is an intended behaviour, what's the rationale behind it in light of the above?
  3. (b) if this is a bug, why does it happen?

note: I've checked the docs for other array functions, and e.g. http://php.net/manual/en/function.compact.php, http://php.net/manual/en/function.array-merge.php etc. show the param list exactly as expected).

  • The spread operator doesn't seem to affect how the function operates, it just controls how PHP assigns the arguments. array_merge only has 1 required argument, array_push requires 2. – Devon Bessemer Jul 09 '18 at 17:28

1 Answers1

4

Well, the great mystery seems to be solved: while poking through the commits in https://github.com/php/php-src/blob/master/ext/standard/array.c, I found this for array_push:

ZEND_PARSE_PARAMETERS_START(1, -1)
    Z_PARAM_ARRAY_EX(stack, 0, 1)
    Z_PARAM_VARIADIC('+', args, argc)
ZEND_PARSE_PARAMETERS_END();

The first line was changed recently, from ZEND_PARSE_PARAMETERS_START(2, -1), making the issue nonexistent.

https://github.com/php/php-src/commit/f7f48643e779111b23b546689b9fbb4e3affe1e7

quote:

php-7.3.0alpha1

array_push() and array_unshift() can now also be called with a single argument, which is particularly convenient wrt. the spread operator.

It seems it was both a documentation error and a missing feature. Yay for PHP 7.3 devs for implementing this!

Community
  • 1
  • 1