On array_slice and array_shift Functions

public function query($query) {
    $stmt = $this->pdo->prepare($query);
    $stmt->execute(array_slice(func_get_args(), 1));
    return $stmt;
Interesting piece of PHP code shown above. Didn't realize you can use array_slice function to extract portion of an array from func_get_args function. My typical way is just using array_shift function to remove the first element.

Instead of
array_slice(func_get_args(), 1);

you can also obtain the same result (a bit longer) by
$args = func_get_args();

However, you just can't simply write in such way show below (the interpreter will throw fatal error) which I am going to elaborate more.

Run your PHP in interactive mode and type the sample code. As shown.
$ php -a
php > print_r(array_shift(array('a', 'b', 'c')));
PHP Fatal error:  Only variables can be passed by reference in php shell code on line 1

Let's assign a temporay variable to the array. Howevery, we only obtain the first element as array_shift function is a modifier function which modify the argument and expect is to be a reference.
php > print_r(array_shift($temp = array('a', 'b', 'c')));
aphp >

The only way is to first assign your array to a variable and modify it.
php > $temp = array('a', 'b', 'c');
php > array_shift($temp);
php > print_r($temp);
    [0] => b
    [1] => c

Conclusion is if you want a portion of an array, just use array_slice function.

No comments:

Post a Comment