QiZhi
QiZhi

Reputation: 15

in_array for PHP not working

I have 2 arrays, DefaultSizes and ExistingSizes that I retrieved from the database. $DefaultSizes have values 'L','M', 'S' and $ExistingSizes has 'S'. (Ran a foreach look to check through the values for both of them)

I want to print out values in $DefaultSizes that are not in $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.

Upvotes: 1

Views: 269

Answers (1)

u_mulder
u_mulder

Reputation: 54831

There's no need for in_array. Use array_diff and shorten your code:

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

Upvotes: 2

Related Questions