简体   繁体   English

PHP的in_array无法正常工作

[英]in_array for PHP not working

I have 2 arrays, DefaultSizes and ExistingSizes that I retrieved from the database. 我有2个数组,我从数据库中检索到的DefaultSizes和ExistingSizes。 $DefaultSizes have values 'L','M', 'S' and $ExistingSizes has 'S'. $ DefaultSizes的值为“ L”,“ M”,“ S”,$ ExistingSizes的值为“ S”。 (Ran a foreach look to check through the values for both of them) (运行一次foreach外观以检查它们的值)

I want to print out values in $DefaultSizes that are not in $ExistingSizes. 我想在$ DefaultSizes中打印出不在$ ExistingSizes中的值。

This is my code: 这是我的代码:

$count = 1;
foreach ($DefaultSizes as &$def)
{
    if(in_array($def['Size'],$ExistingSizes) === false)
    {
        echo "$def[Size]<br>";
        $count++;
    }
}

The value 'S' still gets printed out. 值“ S”仍会打印出来。

There's no need for in_array . 不需要in_array Use array_diff and shorten your code: 使用array_diff并缩短您的代码:

$DefaultSizes = ['L','M','S'];
$ExistingSizes = ['S'];
$not_in_existing = array_diff($DefaultSizes, $ExistingSizes);
print_r($not_in_existing);  // array('L', 'M')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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