检查in_array中的数组值

时间:2017-10-12 19:30:46

标签: php

我正在使用此代码检查数组中是否存在其中一个值:

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

但是现在脚本没有执行或者给出了任何错误。

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

print_r($_SESSION['user_type'])提供beheerder

2 个答案:

答案 0 :(得分:0)

您不会在大海捞针中找到针阵列作为子阵列。如果$_SESSION['bedrijf']始终是数组,则检查交集(至少1个匹配):

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

答案 1 :(得分:0)

由于您的$_SESSION['bedrijf']包含数组,因此可以使用以下代码获取结果。

 <?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
    }

    ?>
相关问题