2011-04-08 16 views

Respuesta

32
if($var == "abc" || $var == "def" || ...) 
{ 
    echo "true"; 
} 

Usar "O" en lugar de "Y" ayudaría aquí, creo que

11

puede utilizar in_array función de php

$array=array('abc', 'def', 'hij', 'klm', 'nop'); 

if (in_array($val,$array)) 
{ 
    echo 'Value found'; 
} 
84

Una forma elegante es la construcción de una matriz sobre la marcha y utilizando in_array():

if (in_array($var, array("abc", "def", "ghi"))) 

El switch statement es también una alternativa:

switch ($var) { 
case "abc": 
case "def": 
case "hij": 
    echo "yes"; 
    break; 
default: 
    echo "no"; 
} 
+1

sí, in_array() es exactamente la forma en que lo haría. –

+1

Esto es lo que necesitaba :) Gracias a Dios por el archivo Stackoverflow;) –

+1

Juro por php3 Solía ​​hacer si ($ var == 'abc' | 'xyz' | 'cbs') tal vez era solo un sueño : p – nodws

11

No sé, por qué quiere usar &&. Hay una solución más fácil

echo in_array($var, array('abc', 'def', 'hij', 'klm', 'nop')) 
     ? 'yes' 
     : 'no'; 
4

puede utilizar el operador booleano o: ||

if($var == 'abc' || $var == 'def' || $var == 'hij' || $var == 'klm' || $var == 'nop'){ 
    echo "true"; 
} 
3

Puede probar esto:

<?php 
    echo (($var=='abc' || $var=='def' || $var=='hij' || $var=='klm' || $var=='nop') ? "true" : "false"); 
?> 
-9

no sé si $ var es una cadena y que desee encontrar sólo aquellas expresiones pero aquí va en ambos sentidos.

Intente utilizar preg_match http://php.net/manual/en/function.preg-match.php

if(preg_match('abc', $val) || preg_match('def', $val) || ...) 
    echo "true" 
+7

-1 ¡Guau! ¿Sabes cuánto sobrecarga te acaba de causar? ¡Dios mío, hombre! –

+0

Sin mencionar los delimitadores faltantes en el patrón. – SOFe

1

Prueba este trozo de código:

$first = $string[0]; 
if($first == 'A' || $first == 'E' || $first == 'I' || $first == 'O' || $first == 'U') { 
    $v='starts with vowel'; 
} 
else { 
    $v='does not start with vowel'; 
} 
0

será bueno utilizar matriz y comparar cada valor de 1 por 1 en bucle. Da la ventaja de cambiar la longitud de su matriz de pruebas. Escriba una función tomando 2 parámetros, 1 es una matriz de prueba y otra es el valor que se probará.

$test_array = ('test1','test2', 'test3','test4'); 
for($i = 0; $i < count($test_array); $i++){ 
    if($test_value == $test_array[$i]){ 
     $ret_val = true; 
     break; 
    } 
    else{ 
     $ret_val = false; 
    } 
} 
0

me encontré con este método ha funcionado para mí:

$thisproduct = "my_product_id"; 
$array=array("$product1", "$product2", "$product3", "$product4"); 
if (in_array($thisproduct,$array)) { 
    echo "Product found"; 
} 
Cuestiones relacionadas