简体   繁体   中英

php in_array giving odd result

I've read all the other articles on in_array, and still don't understand why mine is givng odd results. I'm inheriting this code from someone else, and don't fully understand why they did certain things. When a user logs in, data is grabbed from a db, one of the fields being their "level". 1 is an admin, 2 a regular user, etc. Once the data is grabbed from the db, we put the user level (stored as a:1:{i:0;s:1:"2") into an array:

$user_level = unserialize($this->result['user_level']); 
$_SESSION['unt']['user_level'] = $user_level;

Later we check to see if this is an admin:

error_log(print_r($_SESSION['abc']['user_level']));  //this is always "1"
if (in_array('1', $_SESSION['abc']['user_level'])) {   //should be yes, correct?

Yet somehow the if statement never evaluates as true, even though the SESSION variable is 1. What am I missing?

$_SESSION['abc']['user_level'] doesn't appear to be an array. Looks like you want one of the following.

If gettype($_SESSION['abc']['user_level']) is 'integer':

if ($_SESSION['abc']['user_level']) === 1) {

If gettype($_SESSION['abc']['user_level']) is 'string':

if ($_SESSION['abc']['user_level']) === '1') {

If gettype($_SESSION['abc']['user_level']) is 'string' and its value actually contains the quotes:

if ($_SESSION['abc']['user_level']) === '"1"') {

If it was an array the output would have this structure, not just "1":

Array
(
    [0] => 1
)

Even though I noticed closing bracket } missing from your input string I just assumed that you probably might have missed while copy-pasting .

a:1:{i:0;s:1:"2"

So in_array is not the problem but your input string is the problem .
With display_errors setting Off you would not see any error when you try to unserialize it .

You could use the below function to check if the input is a valid string to unserialize :

//  Copied from http://www.php.net/manual/en/function.unserialize.php
function is_serialized( $str )
{
    return( $str == serialize( false ) || @unserialize( $str ) !== false );
}

Then something along these lines :

    $inputString = 'a:1:{i:0;s:1:"2";}';   //  Is valid and is holding one array of info
//  $inputString = 'a:1:{i:0;s:1:"2"';   //  Invalid as is missing a closing baracket }

if( ! is_serialized( $inputString ) )
{
    echo 'Is not serialized';
}
else
{
    $user_level = unserialize( $inputString );

    $_SESSION['unt']['user_level'] = $user_level;   //  Is an array

//  Note the second argument as was already pointed by @AsksAnyway
    error_log( print_r( $_SESSION['unt']['user_level'] , true ) );

    var_dump( in_array( '1' ,$_SESSION['unt']['user_level']) );

    var_dump( in_array( '2' ,$_SESSION['unt']['user_level']) );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM