2

Is there a way to do this, but in a shorter way? or "more professional" way? Thanks and regards. Check variables is empty (check if one is empty).

if((
empty($varone) || 
empty($vartwo) || 
empty($vthree) || 
empty($vardf) || 
empty($vfgsdgsdal) || 
empty($pasadfsd) || 
empty($efda) 
)) {
    $response = "There is an empty data";
    }else{$response = "NO EMPTY DATA!";}
2
  • Pass variables in array and run loop. if value is empty return message or you can try this. Commented Mar 23, 2021 at 7:43
  • I have added more better way to achieve your goal. Please have a look my answer. Commented Mar 23, 2021 at 7:52

2 Answers 2

2

Firt solution, add values in array and tests if there is empty value

function checkEmptyValueArray($values) {
    return !empty(array_filter($values, function ($value) {
        return empty($value);
    }));
}

$values = [$varone, $vartwo, $vthree, $vardf, $vfgsdgsdal, $pasadfsd, $efda];

if ( checkEmptyValueArray($values) ) {
    $response = "There is an empty data";
} else{
    $response = "NO EMPTY DATA!";
}

An other solution is to use variable-length arguments list

Follow this link for an explanation : https://www.php.net/manual/en/functions.arguments.php

function checkEmptyValueArray(...$args) {
    foreach ( $args as $arg ) {
        if ( empty($arg) ) {
            return true;
        }
    }
    return false;
}

if ( checkEmptyValueArray($varone, $vartwo, $vthree, $vardf, $vfgsdgsdal, $pasadfsd, $efda) ) {
    $response = "There is an empty data";
} else{
    $response = "NO EMPTY DATA!";
}
Sign up to request clarification or add additional context in comments.

1 Comment

I don't know which of your solutions i prefer, both are great ^^.
1

Try this more professional, simple & elegant way:

if (in_array("", array($varone, ..., $varN)) {
   $response = "There is an empty data";
} else {
   $response = "There is not any empty data";
}

Happy coding :)

3 Comments

It also works for the values you mentioned. Tested :)
Well with 0 it does not work (on php8), my bad for null ;) 3v4l.org/3vsOV
What makes this "more professional"? I don't even know what that means in this context, tbh. Also, empty() checks for more things than just an empty string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.