5

我的脚本输出一个数组:

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

有时其中的键$person没有值 - 我想检查一下。$person['age']但是,我不会给出关于or的鸡块$person['weight'],我只想检查数组中的其他键是否为空:

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

为什么这不起作用?

4

5 回答 5

3

这匹配所有键:

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

你可能想要:

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

或类似的东西(规模更好......):

if (!in_array($key, array('age', 'weight')))
于 2013-07-16T17:24:02.087 回答
2

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>";
        }
    }
}

Codepad: http://codepad.org/hEHVru4a

Hope this helps!

于 2013-07-16T17:26:36.847 回答
2

if 表示 key 是否age不是weight。如果这是正确的;

所以试试这个:

foreach ($person as $key => $value) {
    if (!in_array($key, array('age','weight')) {
        if ($value == FALSE) {
            echo $key . ' is empty';
        }
    }
}
于 2013-07-16T17:29:35.360 回答
1

Because if the key does equal 'age' it will still NOT equal weight, and tell you that you dun goofed. And vice-versa. Try this:

if ( !in_array ($key, array('age','weight')) ) {
于 2013-07-16T17:26:11.307 回答
1

您需要更改 || 到 &&。事实上,if 语句对于年龄和体重都是正确的

于 2013-07-16T17:25:05.800 回答