validation - PHP if OR multiple conditions get which is true
Get the solution ↓↓↓To avoid multipleif
conditions orloop
, is there a way to tell which condition is true:empty($data1)
orempty($data2)
?
// Validation
if ( empty($data1) || empty($data2) ) {
echo 'Required data is missing';
}
Answer
Solution:
i prefer to check per field if there is an empty or null value for example :
if(empty($data1)){
echo "data1 is missing";
}
else if(empty($data2)){
echo "data2 is missing";
}
else {
//if all data is not null or empty
}
or you can make a function to check there is empty or not
Answer
Solution:
Capture the results of each call toempty()
to see which condition was true later in your code:
$data1IsEmpty = empty($data1);
$data2IsEmpty = empty($data2);
if ($data1IsEmpty || $data2IsEmpty) {
echo 'Required data is missing';
if ($data1IsEmpty) {
echo 'data1 is empty';
}
if ($data2IsEmpty) {
echo 'data2 is empty';
}
}
Answer
Solution:
I am sure you are trying to validate a login form. Whatever the case, @stephen's answer is your best bet. But if you are just checking random fields. Here's a workaround for any number of field checks
function isEmpty($field){
return empty($field) ? "$field is required" : false;
}
$emptyInputs = [];
foreach($formInputs as $input){
// $formInputs == data from form
if($empty = isEmpty($input)){
$emptyInputs[] = $empty;
}
}
return $emptyInputs;
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: installation failed, reverting ./composer.json and ./composer.lock to their original content.
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.