I have three variables:
$var1
$var2
$var3
I'm actually looking for the best way to check if only one of these three variables is not empty and the two others are empty.
Is that possible to do this with one if
only? If not, then what's the best way?
The variables all contain text.
The empty() function checks whether a variable is empty or not. This function returns false if the variable exists and is not empty, otherwise it returns true. The following values evaluates to empty: 0.
The typeof operator for undefined value returns undefined . Hence, you can check the undefined value using typeof operator. Also, null values are checked using the === operator. Note: We cannot use the typeof operator for null as it returns object .
Use the length property to check if a string is empty, e.g. if (str. length === 0) {} . If the string's length is equal to 0 , then it's empty, otherwise it isn't empty.
You can convert variable into array and exclude empty variables using array_filter()
. Then use count()
after the filter.
if(count(array_filter(array($var1,$var2,$var3)))==1){
//only 1 variable is not empty
}
Check Fiddle link
Booleans return 0 and 1 with array_sum()
if (array_sum(array(empty($var1), empty($var2), empty($var3))) == 1)
{
echo "one is empty" ;
}
ETA: This is a simpler way:
if (!empty($var1) + !empty($var2) + !empty($var3) == 1) {
echo "1 is not empty" ;
}
ETA 2: We don't need the negative signs
if (empty($var1) + empty($var2) + empty($var3) == 2) {
echo "1 is not empty" ;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With