1

I have the following code:

$path = ltrim($_SERVER['REQUEST_URI'], '/');
$elements = explode('/', $path);
var_dump($elements);
echo is_array($elements) ? 'true' : 'false';
$elements=array_shift($elements);

explode(delimeter, string) should return array. And it is returning as is_array(bool) returns true, but array_shift(array) gives following error:

Warning
: array_shift() expects parameter 1 to be array, string given in

Why is this happening even when $elements is an array?

PHP 7.2.19

1 Answer 1

2

The array_shift()-method shifts the first value of the array off and returns it. So if you run

$elements = array_shift($elements);

the contents of $elements will be the first element of the array (in your case a string).

You can use it like this:

$path = ltrim('/path/to/resource', '/');
$elements = explode('/', $path);
$first_element = array_shift($elements);
var_dump($first_element, $elements);

And the first element of the array will be in the variable $first_element. The $elements-array will no longer contain that element.

Demo: https://3v4l.org/DHcsJ

More info about the method can be found in the official documentation.

Sign up to request clarification or add additional context in comments.

Comments

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.