I am doing with Laravel 5. And the problem I am facing is that I have an array in session and now I want to remove a single element from that array and for the sake I am using array_diff
function.
When I get array from session it's in the form like:
["4","5","6"]
But when I try to remove element '5' from array it deforms the array and the result then is:
{"0":"4","2":"6"}
My code is:
array_diff($arr, array(5))
The result is same with unset([$index])
also.
The real code:
Session::push('compare.products', $id);
$compare = Session::get('compare');
if(($key = array_search($id, $compare['products'])) !== false) {
unset($compare['products'][$key]);
return $compare['products'];
}
If you want to keep correct indexes you have to call array_values
after the unset.
In your case, it will be :
Session::push('compare.products', $id);
$compare = Session::get('compare');
if(($key = array_search($id, $compare['products'])) !== false) {
unset($compare['products'][$key]);
return array_values($compare['products']);
}
In a general case, it's :
$array = array(0, 1, 2, 3);
unset($array[2]);
$array = array_values($array);
var_dump($array);
/* array(3) {
[0]=>
int(0)
[1]=>
int(1)
[2]=>
int(3)
} */