简体   繁体   中英

Check array values in in_array

I am using this code to check if one of the values in the arrays are present:

<?php
if (in_array($_SESSION['bedrijf'], array(
    "torza",
    "thure",
    "mb"
)) && in_array($_SESSION['user_type'], array(
    "beheerder",
    "administratie",
    "kantoor",
    "werkplaats"
))) {
    echo 'execute script';
}
?>

But now the script is not executed or any errors given.

print_r($_SESSION['bedrijf']) gives Array ( [0] => mb [1] => thure [2] => torza )

print_r($_SESSION['user_type']) gives beheerder

You will not find the needle array as a sub-array in the haystack. If $_SESSION['bedrijf'] is always an array, then check for an intersection (at least 1 match):

if (array_intersect($_SESSION['bedrijf'],
                    array("torza","thure","mb")) &&
    in_array($_SESSION['user_type'],
             array("beheerder","administratie","kantoor","werkplaats")))
{
    echo 'execute script';
}

Because your $_SESSION['bedrijf'] contains an array, its possible to get your result with the following code.

 <?php
    $allowScript = false;
    if(is_array($_SESSION['bedrijf']))
    {
        foreach($_SESSION['bedrijf'] as $bedrijf)
        {
            if (in_array($bedrijf, array("torza","thure","mb")) && in_array($_SESSION['user_type'], array("beheerder", "administratie", "kantoor","werkplaats")
            {
                $allowScript = true;
                // Execute Script!
            }
        }
    }

    if($allowScript === TRUE)
    {
        // Execute script
    }
    else
    {
        // Not allowed
    }

    ?>

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