Reputation: 6822
How do I check, if a value already exists within a Session array? I'm trying store active tree objects within a Session array to toggle them on and off:
public function postSelected()
{
$id = Input::get('id');
if (Session::has('user.selection', $id)) { // check?
Session::pull('user.selection', $id);
} else {
Session::push('user.selection', $id);
}
return Response::json(Session::get('user.selection'), 200);
}
Any ideas?
Upvotes: 1
Views: 3931
Reputation: 219938
Assuming what you're trying to do is akin to a toggle (remove if present, add if missing):
$index = array_search($id, $selection = Session::get('user.selection', []));
if ($index !== false)
{
array_splice($selection, $index, 1);
}
else
{
$selection[] = $id;
}
Session::set('user.selection', $id);
Upvotes: 4