PHP explode 函数只允许我在搜索 in_array 时检测数组的第一项。为什么?

PHP explode function only allows me to detect first item of array when i search in_array. Why?

我已将复选框数据转换为字符串以存储在我的数据库中。

但是,当我尝试使用 explode 函数将字符串转换回数组时,我无法搜索 in_array 除了第一项以外的任何内容。为什么?

$rolepref = explode(',', $roles);
print_r($rolepref) = [0] Strategy [1] Operations
if (in_array("Strategy", $rolepref) { echo "yes" } => Will echo yes
if (in_array("Operations", $rolepref) { echo "yes" } => Does not work

我在这里错过了什么?提前致谢!

很可能您在分解数据后有空格。尝试用trim

$roles = "Strategy, Operations";
$rolepref = array_map('trim', explode(',', $roles)); //trim and explode data
if (in_array("Strategy", $rolepref)) { echo "yes"; }
if (in_array("Operations", $rolepref)) { echo "yes"; }

您的 $roles 可能是:"Strategy, Operations",当您 explode 使用 , 时,它会给您两个元素:"Strategy"" Operations"...请注意单词 Operations 之前的额外 space。所以 trim space 在比较每个元素之前。

$roles = "Strategy, Operations"; // lets say $rolepref = array_map('trim', explode(',', $roles)); if (in_array("Strategy", $rolepref)) { echo "yes"; } if (in_array("Operations", $rolepref)) { echo "yes"; }

in_array returns 如果找到 EXACT 值则为真。 您的数组可能不完全相同,请尝试使用 trim()

清理它

下面的代码有效。

$array = [
    0 => 'Strategy',
    1 => 'Operations',
];

if (in_array("Strategy", $array))
{
    echo "yes s <br />";
}

if (in_array("Operations", $array))
{
    echo "yes o <br />";
}