I am trying to use unset/array_splice
to remove an index of an item from an array, in the context of Laravel sessions.
What I have is:
Check if
class
session key existsIf so, get it, and loop through it
If that particular index's element (a string) matches the input string (from an AJAX request), unset it, and
put
the new unsetted array BACK to the session
This operation, in theory (story of my life), should remove an item from the cart.
// Remove the item [if exists]
if(Session::has('class')) {
$classes = Session::get('class');
foreach($classes as $index => $class) {
if($data['class'] === $class) {
array_splice($classes, $index, $index - 1);
Session::put('class', $classes);
return Response::json(array(
'success' => true,
'code' => 1,
'message' => $data['class'] . ' removed from cart'
)
);
}
}
}
The data within the class
session looks like this:
[
"ECEC 471 Introduction to VLSI Design Lab",
"ECEC 471 Introduction to VLSI Design Lecture",
"ECEC 413 Introduction to Parallel Computer Architecture Lecture",
"ECEC 457 Security in Computing Lecture & Recitation"
]
I traced the code logically a couple times, but it does not unset the item. I know the string is matched, since my JSON response from the shown query is returned.
EDIT:
Ok, so I made a little breakthrough.
I forgot to assign the key to
put
in the session, so I've changed it to this:Session::put('class', $data)
Next, due to how the indices things work with
array_splice
, the unsetting works for all indices greater than 1. If the current index you want to unset is0
or1
, it fails, since respectively, the "new" index turns to-1
and0
..