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.
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.
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
unsetdoesn't return anything. You're probably looking forarray_shift.