1

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?

1 Answer 1

4

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);
Sign up to request clarification or add additional context in comments.

5 Comments

That easy! What are those brackets at the end of the session doing? Did the trick, thanks! I've already tried in_array, but I have't been successful.
@wiesson - Those brackets are short array notation (it's equivalent to array(), which creates an empty array). Basically, it ensures that you're dealing with an array.
The array_pull will not remove the desired item from my array. Anything special, I have to notice?
I've added Log::info($selection) before and after and it is still the same, also my tree won't update. (I'm storing strings, not integers, if this helps)
@wiesson - Whoops! array_pull works with keys, not values. I updated my answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.