Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply logic to only certain keys in array using PHP's foreach

My script outputs an array:

$person = array(
    'name' => 'bob',
    'age' => '27',
    'sex' => 'male',
    'weight' => 'fat'
    // ...etc.
);

Sometimes the keys in $person have no values - and I want to check for this. However, I don't give a chicken nugget about $person['age'] or $person['weight'], I only want to check the other keys in the array aren't empty:

foreach ($person as $key => $value) {
    if ( $key != 'age' || $key != 'weight' ) {
        if ( empty($value) ) {
            echo 'you dun goofed';
        }
    }
}

Why isn't this working?

like image 806
izolate Avatar asked Jul 16 '13 17:07

izolate


1 Answers

This matches all keys:

if ( $key != 'age' || $key != 'weight' )

You probably want:

if ( $key != 'age' && $key != 'weight' )

or something like (scales a bit better...):

if (!in_array($key, array('age', 'weight')))
like image 170
jeroen Avatar answered Sep 28 '22 00:09

jeroen