Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if two variables are not empty in PHP

I want to echo variables if either of them aren't empty.

I have written the following PHP but they aren't being shown when the variables aren't empty:

if(!empty($this->element->videos||$this->element->productdownloads)) {
    echo $this->element->videos; 
    echo $this->element->productdownloads; 
}
like image 418
RustyIngles Avatar asked Mar 10 '26 20:03

RustyIngles


2 Answers

When checking with the OR operator (||) the code will execute if one or none of them is empty. But you echo both variables even if one of them is empty.

What I think you want to do is use the AND operator(&&). This way, the code will only execute if none of the variables are empty.

<?php   if(!empty($this->element->videos) && !empty($this->element->productdownloads)) {
    echo $this->element->videos; 
    echo $this->element->productdownloads; }
?>

if you still want to show videos, even if productdownloads is empty (and vice versa), you could do a seperate if for each of them, like this:

if(!empty($this->element->videos){
    echo $this->element->videos; 
}
if(!empty($this->element->productdownloads){
    echo $this->element->productdownloads; 
}

edit: minor grammatical fixes

like image 188
kscherrer Avatar answered Mar 12 '26 08:03

kscherrer


    <?php   
      if(!empty($this->element->videos) || !empty($this->element->productdownloads)) {
        echo $this->element->videos; 
        echo $this->element->productdownloads; 
      }
    ?>
like image 39
Mike Avatar answered Mar 12 '26 10:03

Mike



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!