php empty array if statement [closed]
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.
精彩评论