0

I have this array:

$cars = array("Volvo", "BMW", "Toyota");
$cars_without_volvo=unset($cars[0]);

print_r($cars);
print_r($cars_without_volvo);die;

I need both the $cars and $cars_without_volvo to later use. The above doesnot seem to work.

1
  • unset doesn't return anything. You're probably looking for array_shift. Commented Sep 11, 2017 at 10:59

2 Answers 2

3

You can copy the array to $cars_without_volvo and unset from that, then you'd have two different arrays. unset() doesn't return anything, it's used to unset elements or variables directly.

This of course assumes that Volvo is always the first element in the $cars array, because we unset the first element.

$cars = array("Volvo", "BMW", "Toyota");
$cars_without_volvo = $cars;
unset($cars_without_volvo[0]);

print_r($cars);
print_r($cars_without_volvo);

Outputs

Array (
    [0] => Volvo
    [1] => BMW
    [2] => Toyota
)
Array (
    [1] => BMW
    [2] => Toyota
)

You can also find the key for the Volvo element dynamically, by using array_search() (demo), by replacing the unset() line above with the one below.

unset($cars_without_volvo[array_search("Volvo", $cars_without_volvo)]);

Using array_shift() as shown in the other answer is most likely the better approach - if the element you wish to remove is the first one. If you want to remove elements in a difference index than the first or last, using this approach might be easier.

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

Comments

3

array_shift() removes the first element from an array, array_pop removes it from the end:

<?php

$cars = array("Volvo", "BMW", "Toyota");
$volvos = array_shift($cars);

var_dump($cars, $volvos);

Output:

array(2) { [0]=> string(3) "BMW" [1]=> string(6) "Toyota" } string(5) "Volvo"

Check it out here: https://3v4l.org/nZqul Docs here: http://php.net/manual/en/function.array-shift.php

1 Comment

This is a better approach than copying the array and then unsetting the first element, that my answer (based on OPs code) is using.

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.