user1621945
user1621945

Reputation: 35

if in_array not working as expected?

'Permissions' is a comma separated list of integers, ex: 1,10,70,1000 The permissions string is shoved into $_SESSION, and then returned as $type after exploding

$permissions = $_SESSION['user']['permissions'];
$type = explode(",", trim($permissions));

if(in_array(1337, $type)){
echo '<li><a href="protectedpage.php">Page Name</a></li>';}

For some reason, nothing is echoed. I've echoed $_SESSION['user']['permissions'] and gotten 1337

I've done print_r($type) and gotten Array ( [0] => 1337 )

So why isn't in_array returning true?

Upvotes: 0

Views: 4166

Answers (2)

Jordan Mack
Jordan Mack

Reputation: 8763

I executed the following code, and it worked fine.

$permissions = '1,10,70,1000,1337';
$type = explode(",", trim($permissions));

if(in_array(1337, $type))
{
    echo 'found';
}

I recommend that you check to make sure that $permissions is what you expect it to be in the cases where it is failing. Try echoing it if the condition doesn't work, so you can check. You may also want to remove any spaces just in case that is fouling things up.

$permissions = $_SESSION['user']['permissions'];
$type = explode(",", str_replace(' ', '', $permissions));

if(in_array(1337, $type))
{
    echo 'found';
}
else
{
    echo $permissions;
}

Upvotes: 2

WhoaItsAFactorial
WhoaItsAFactorial

Reputation: 3558

Try putting 1337 into quotes, '1337'. I believe that will fix your problem.

Upvotes: 0

Related Questions