Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check whether only one out of three variables is not empty?

Tags:

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.

like image 831
cetipabo Avatar asked Sep 14 '16 07:09

cetipabo


People also ask

Is used to check whether the variable is empty or not?

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.

How do you check if a variable is not empty in Javascript?

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 .

Is not empty JS?

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.


2 Answers

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

like image 92
Haresh Vidja Avatar answered Sep 16 '22 22:09

Haresh Vidja


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" ;
}
like image 21
Dominique Lorre Avatar answered Sep 20 '22 22:09

Dominique Lorre