PHP: eğer boş &

2 Cevap php

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?

2 Cevap

İşte dört durumda da farklı bir şey yapmak için kompakt bir yol:

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

Bunun yerine bir ifade kullanmak istiyorsanız, ?: yerine kullanabilirsiniz:

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

Kriterleri bir sürü içeren bazı durumlarda, hatta sadece birkaç durumlarda, bir anahtarı kullanarak düşünün.

switch( true ){

    case ( !empty($youtube) && !empty($link) ):{
        // Nothing is empty...
        break;
    }

    case ( !empty($youtube) && empty($link) ):{
        // One is empty...
        break;
    }

    case ( empty($youtube) && !empty($link) ):{
        // The other is empty...
        break;
    }

    case ( empty($youtube) && empty($link) ):{
        // Everything is empty
        break;
    }

    default:{
        // Even if you don't expect ever to use it, it's a good idea to ALWAYS have a default.
        // That way if you change it, or miss a case, you have some default handler.
        break;
    }

}

Eğer aynı eylemi gerektiren birden fazla olgu varsa, onları yığını ve mola atlayabilirsiniz; flowthrough için. Sadece belki / * * aracılığıyla Akan gibi bir yorum koymak / yüzden bilerek yapıyor hakkında açık demektir.

{} Durumlarda çevresinde gerekli, ama onlar okunabilirliği ve kod katlama için güzel olmadığını unutmayın.

Anahtarı hakkında daha fazla: http://php.net/manual/en/control-structures.switch.php