cetipabo cetipabo - 2 months ago 7
PHP Question

How can I check whether only 1 out of 3 vars is not empty?

I have 3 vars:

$var1
$var2
$var3


I'm actually looking for the best way to check if only one of these 3 var is not empty and the 2 others are empty.

Is that possible to do this with one
if
only? If not, then what's the best way?

The vars all contain text.

Answer

You can convert variable into array and exclude empty variables using array_filter(). and use count() after filter

if(count(array_filter(array($var1,$var2,$var3)))==1){
   //only 1 variable is not empty
}

Check Fiddle link