Apply logic only to specific keys in an array using PHP foreach

My script outputs an array:

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

Sometimes the keys in $person have no meaning - and I want to check it. However, I don't give the chicken nugget about $person['age'] or $person['weight'] , I just want to check that the other keys in the array are not empty:

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

Why is this not working?

+4
source share
5 answers

This corresponds to all the keys:

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

You probably want:

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

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

 if (!in_array($key, array('age', 'weight'))) 
+3
source

You probably want to check if both of them are empty:

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

Code:

 foreach ($person as $key => $value) { if ( $key != 'age' && $key != 'weight' ) { if ( empty($value) ) { echo "$key field is empty<br>"; } } } 

Codefall: http://codepad.org/hEHVru4a

Hope this helps!

+2
source

If the key is not age or weight . If this is correct,

try the following:

 foreach ($person as $key => $value) { if (!in_array($key, array('age','weight')) { if ($value == FALSE) { echo $key . ' is empty'; } } } 
+2
source

You need to change || to & &. Be that as it may, the statement if will be true for both age and weight

+1
source

Because if the key is equal to 'age' , it will still NOT equal the weight, and will tell you that you worked. And vice versa. Try the following:

 if ( !in_array ($key, array('age','weight')) ) { 
+1
source

Source: https://habr.com/ru/post/1491706/


All Articles