开发者

php empty array if statement [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center. Closed 9 yea开发者_如何学Pythonrs ago.

Hi guys my if statement is not working. I want to basically do nothing is the array is empty or do something if it has values. All that happens is "no extras selected" is displayed even if i select extras

if (empty($extras)) { 
    $message .="<br /> No extras selected <br />";
    } else { 
    foreach($_POST['extras'] as $extra)
    {
      $message .="<br />Extras: ".$extra."<br />";

    } 
    }


I'm assuming this is a typo, as according to your code $extras is never set.

You should be using

if (empty($_POST['extras'])) {


Possibly $extras variable is empty, but you're iterating through $_POST['extras'] which is not the same.


I haven't tested this, but you can try an if(!isset($extras[0]))


What about

if ( empty($_POST['extras']) ) { ... }

?

Have you declared $extras variable before ?


if(!empty($array)){
//do something
}else{
//donothing

}

Please try this.,....


You can try also with the is_array() function. Documentation here


If you've assigned an empty array to the $extras variable in your code (for example $extras = array(), then you're essentially checking the assignment of $extras, rather than the length of the array assigned thereto.

This should work for you:

if(count($extras) == 0) {  
    // Your code here...
}


I think your code should be this:

if (array_key_exists('extras', $_POST) and // check that the element exists in the $_POST array
    !empty($_POST['extras'])) { // check that it is not empty
     foreach ($_POST['extras'] as $extra) {
        $message .="<br />Extras: " . $extra . "<br />";
     }
} else {
    $message .="<br /> No extras selected <br />";
}

Currently the logic in your code is backwards.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜