Home » Php » Check if atleast one field is not empty in PHP

Check if atleast one field is not empty in PHP

Posted by: admin February 25, 2020 Leave a comment

Questions:

I have these fields: weight, size_1, size_2, size_3

How can I check so minimum one of these fields are filled.

If its under the minimum then it should output “Error, fill one atleast”

I can do this with long if statements, that checks for empty, but is their a better way?

The fields come from an form submission, so it looks like this to get them:

$_POST['weight'];
$_POST['size_1'];
$_POST['size_2'];
$_POST['size_3'];
How to&Answers:

Assuming they are all in an array:

function check_for_input($array){
     foreach($array as $value){
           if($value != "") return true;
     }
     return false;
}

Use it like so:

if(check_for_input($_POST)){ /*...*/ }
else { die("Error, fill one at least"); }

Update with filter:

Assuming they are all in an array:

function check_for_input($array, $filter){
     foreach($array as $key=>$value){
           if($value != "" && in_array($key, $filter)){ 
                return true;
           }
     }
     return false;
}

Use it like so:

$filter = array('weight', 'size_1', 'size_2', 'size_3', /*...*/);
if(check_for_input($_POST, $filter)){ /*...*/ }
else { die("Error, fill one at least"); }