Foo SK Foo SK - 7 months ago 7
PHP Question

php re-sort array key after remove item from session array

I have $_SESSION['items'] to stored cart items as structure below:

print_r($_SESSION['items']):

Array
(
[0] => Array
(
[p_name] => Germany Fully Synthetic Engine Oil 5w40, 4L
[p_code] => 15177651
[p_coverImg] => 13-1460446338-kMTXa.jpg
[p_id] => 13
[p_price] => 126.00
[p_qty] => 2
)

[1] => Array
(
[p_name] => BetterBody Foods Organic Cold Pressed Extra Virgin Coconut Oil
[p_code] => 15599414
[p_coverImg] => 9-1460445708-6XlfS.jpg
[p_id] => 9
[p_price] => 278.40
[p_qty] => 5
)

[2] => Array
(
[p_name] => X-Dot Motorbike Helmet G88 + Bogo Visor (Tinted)
[p_code] => 2102649
[p_coverImg] => 12-1460446199-wI5qx.png
[p_id] => 12
[p_price] => 68.00
[p_alt-variation-1] => Blue
[p_alt-variation-2] => L
[p_qty] => 2
)


)

so to remove item I use
unset($_SESSION['items'][$arr_key]);


let says I
unset($_SESSION['items'][0]);
from above array, after all I
print_r($_SESSION['items'])
, the array key is not starting with [0] anymore:

Array
(
[1] => Array
(
[p_name] => BetterBody Foods Organic Cold Pressed Extra Virgin Coconut Oil
[p_code] => 15599414
[p_coverImg] => 9-1460445708-6XlfS.jpg
[p_id] => 9
[p_price] => 278.40
[p_qty] => 5
)

[2] => Array
(
[p_name] => Wonder Belt Set (2pcs)
[p_code] => 33134567
[p_coverImg] => 2-1460445193-vZwGV.jpg
[p_id] => 2
[p_price] => 199.00
[p_qty] => 1
)

)


how can I restore these session array stating with key
0
again after remove certain item?

Answer

You should use array_values as

array_values($_SESSION['items']);