PHP: if !empty & empty


Question

So i have this form.. With 2 fields. "Youtube" and "link" I want to do if you have filled in YouTube, it should do this:

if(!empty($youtube)) {
 if ($pos === false) { 
 echo "Du skal indtaste youtube et URL, som starter med 'http://www.youtube.com/watch?..<br>";
 echo "<br> Har du ikke din video på YouTube, skal du ikke udfylde feltet, men kun 'Link' feltet.<br><br>";
 echo "<a href='javascript:history.back();'>Gå tilbage</a>";
 }

}

This do its job, but i also want to check on the same if(), if nothing in link. So ive did this:

    if(!empty($youtube) && empty($link)) {
     if ($pos === false) { 
     echo "Du skal indtaste youtube et URL, som starter med 'http://www.youtube.com/watch?..<br>";
     echo "<br> Har du ikke din video på YouTube, skal du ikke udfylde feltet, men kun 'Link' feltet.<br><br>";
     echo "<a href='javascript:history.back();'>Gå tilbage</a>";
     }
}

But what if i want to check the opposite, if theres something in LINK and nothing in youtube? And if i want to check if theres nothing at all in those two?

1
11
5/2/2010 1:59:45 PM

Accepted Answer

if(!empty($youtube) && empty($link)) {

}
else if(empty($youtube) && !empty($link)) {

}
else if(empty($youtube) && empty($link)) {
}
19
2/27/2010 11:00:08 AM

Here's a compact way to do something different in all four cases:

if(empty($youtube)) {
    if(empty($link)) {
        # both empty
    } else {
        # only $youtube not empty
    }
} else {
    if(empty($link)) {
        # only $link empty
    } else {
        # both not empty
    }
}

If you want to use an expression instead, you can use ?: instead:

echo empty($youtube) ? ( empty($link) ? 'both empty' : 'only $youtube not empty' )
                     : ( empty($link) ? 'only $link empty' : 'both not empty' );

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon