0

So, I was designing a function that can take multiple arguments via the spread operator (...$arg)

but it can also take a simple input array. I want to access the first element of the array with the array_slice() method, but it doesn't work as expected:

    // This is what the spread argument passes into the function if it gets a single array
    $arg = [
      ['value1', 'value2', 'valueN'],  
    ];

    // Accessing first element via array_slice:
    var_export( array_slice($arg, 0, 1) );

Expected result:

     array (
       0 => 'value1',
       1 => 'value2',
       2 => 'valueN',
     )

The result is basically equal to the input array:

    array (
      0 => 
      array (
        0 => 'value1',
        1 => 'value2',
        2 => 'valueN',
      ),
    )

I know I can just simply access the 0th element ($arg[0]) to get the first item, but I'm curious why array_slice() doesn't work as I would expect. What am I missing here?

2 Answers 2

2

You are expecting the first value from your array. array_slice return the sliced array. You can use array_shift instead which will shifts the first value of the array off and returns it.

print_r(array_shift($arg));

Output:

array (
       0 => 'value1',
       1 => 'value2',
       2 => 'valueN',
     )
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! Using current($arg) also does the job.
1

It's working as expected. It's returning the first element of your $arg array, which is the array with the key 0 containing an array by itself and not the contents of the first element. You're just misunderstanding how array_slice actually works.

array (
  0 => 
  array (
    0 => 'value1',
    1 => 'value2',
    2 => 'valueN',
  ),
)

1 Comment

Ah, I get it now, it always returns an array. I don't know what I was thinking... thanks for the answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.