2

There is an array of user states stored in the session. This works:

<?php if ($_SESSION['_app_user']['data']['state']['1']) { ?>

  <p>User has state 1</p>

<?php } ?>

But, selecting multiple states doesn't:

<?php if ($_SESSION['_app_user']['data']['state']['1,6,10']) { ?>

  <p>User has state 1 or 6 or 10</p>

<?php } ?>

How can you check on multiple states?

3 Answers 3

4

By checking multiple.

You may find it easier to store the least common denominator to a temporary variable:

$s = $_SESSION['_app_user']['data']['state'];
if(isset($s[1]) || isset($s[6]) || isset($s[10])) {
    echo 'Tahdah!';
}
unset($s);

Also, please use quotes for your strings. It makes code clearer, and saves the PHP interpreter a bit of effort guessing that you mean a string instead of, say, a constant named _app_user :)

Sign up to request clarification or add additional context in comments.

2 Comments

What do you think about the comment from Stefan K about using array_key_exists?
I'm sure you've already arrived at this, but yeah. isset and array_key_exists have slightly different behavior, but isset has the better performance, if its behavior is acceptable.
1

May be it's better to use "array_key_exists" function to check if the given index exists in the array. See Example #2 array_key_exists() vs isset(). https://www.php.net/manual/en/function.array-key-exists.php

7 Comments

How would you implement array_key_exists with the example I posted? Or are you saying I should use Matchu's solution with array_key_exists instead of isset?
if(array_key_exists(1, $s) || ...)
Yes, Matchu's solution with array_key_exists instead of isset.
Thanks Stefan! I am curious why it would be better?
If you don't play with null value inside the array(), isset will be much faster as it's not a function. :) I personally never use array_key_exists()... for performance reasons.
|
1

You could also use array_intersect to check an array of states against your user states. For example:

$user_states = $_SESSION['_app_user']['data']['state'];
$check_states = array( 1, 6, 10 );

$matches = array_intersect(array_keys($user_states), $check_states);
if(!empty($matches))
{
    echo "User has valid states: \n";
    foreach($matches as $_state)
    {
        echo " - {$_state}\n";
    }
}
else
{
    echo "Sorry. Not found.";
}

The function checks whether any two elements in the arrays match, and returns all the matches. Meaning that in that code, the $matches array would be a list of all the states that the user has and are in your list.

2 Comments

Thanks! I couldn't get this working properly but I like the approach.
No problem. Let me know if I can help get it sorted out.

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.