m1755
m1755

Reputation: 175

Check an array of session values in PHP

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?

Upvotes: 2

Views: 1811

Answers (3)

Atli
Atli

Reputation: 7930

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.

Upvotes: 1

Stefan K
Stefan K

Reputation: 47

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

Upvotes: 1

Matchu
Matchu

Reputation: 85794

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 :)

Upvotes: 4

Related Questions