2010-02-27 9 views
8

Así que tengo este formulario ... Con 2 campos. "Youtube" y "enlace" Quiero hacer si ha rellenado YouTube, se debe hacer esto:PHP: si! Vacío y vacío

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>"; 
} 

}

Este hacer su trabajo, pero que también desee comprobar en el mismo si(), si nada en el enlace. Así ive hizo esto:

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>"; 
    } 
} 

Pero lo que si quiero comprobar el contrario, si es que hay algo en el LINK y nada en youtube? Y si quiero verificar si no hay nada en absoluto en esos dos?

Respuesta

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

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

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

Aquí está una manera compacta para hacer algo diferente en los cuatro casos:

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

Si desea utilizar una expresión en lugar, puede utilizar ?: lugar:

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

Para varios casos, o incluso algunos casos que involucran muchos criterios, considere usar un interruptor.

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; 
    } 

} 

Si tiene múltiples casos que requieren la misma acción, puede apilarlos y omitir el corte; para fluir Solo pon un comentario como/* Fluyendo */para que seas explícito sobre hacerlo a propósito.

Tenga en cuenta que {} alrededor de las cajas no son necesarias, pero son agradables para la legibilidad y el plegado del código.

Más información sobre el interruptor: http://php.net/manual/en/control-structures.switch.php

Cuestiones relacionadas