-2

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']; 
}
RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
Ali Shahzad
  • 5,163
  • 7
  • 36
  • 64

1 Answers1

0

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)
} */ 

https://stackoverflow.com/a/369761/4682796

Community
  • 1
  • 1
jmgross
  • 2,306
  • 1
  • 20
  • 24
  • How exactly does this answer the question? – jeroen Apr 09 '15 at 09:15
  • `{"0":"4","2":"6"}` seems to be a kind of var_dump like `["0"=>"4","2"=>"6"]`. And when he says _it deforms the array_ I was thinking that my answer solves the issue with a correct indexed array – jmgross Apr 09 '15 at 09:18
  • I didn't noticed that it was a JSON output... I was too much focus on PHP directly... Thk ^^ – jmgross Apr 09 '15 at 09:26