2010-03-13 19 views

Respuesta

73

Usando if?

if(isset($something['say']) && $something['say'] == 'bla') { 
    // do something 
} 

Por cierto, está asignando un valor con la tecla say dos veces, por lo tanto, la matriz se traducirá en una matriz con un solo valor.

219

Se puede utilizar la función de PHP in_array

if(in_array("bla" ,$yourarray)) 
{ 
    echo "has bla"; 
} 
+5

¿Es posible tener una matriz con claves idénticas? ¿No sobrescribiría el segundo valor el original? – Citricguy

5

Para comprobar si el índice se define: isset($something['say'])

+0

No entiendo la intención de esta respuesta. ¿Cómo se logra el objetivo de verificar el valor de un índice? –

+0

Buena pregunta. Esto no responde la pregunta en absoluto, como está escrito. No recuerdo, pero dado que respondí unos 3 minutos después de que se formuló originalmente la pregunta, supongo que OP modificó su pregunta original para que quede más clara, dentro del límite de edición inicial antes de que se registre como una edición. Si eso tiene algún sentido. – echo

0

Bueno, para empezar una matriz asociativa sólo puede tener una clave definida de una vez, por lo que esta matriz haría nunca existir De lo contrario, simplemente use in_array() para determinar si ese elemento de matriz específico se encuentra en una matriz de posibles soluciones.

4

Puede probar si una matriz tiene un elemento determinado o no con isset() o incluso mejor array_key_exists() (la documentación explica las diferencias). Si no puede estar seguro de si la matriz tiene un elemento con el índice "decir", debe probarlo primero o puede recibir mensajes de "advertencia: índice indefinido ....".

En cuanto a la prueba de si el valor del elemento es igual a una cadena, puede usar == o (nuevamente a veces mejor) el operador de identidad === que no permite type juggling.

if(isset($something['say']) && 'bla'===$something['say']) { 
    // ... 
} 
+0

array_key_exists es siempre mejor solución – AjayR

1
<?php 
if (in_array('your_variable', $Your_array)) { 
    $redImg = 'true code here'; 
} else { 
    $redImg = 'false code here'; 
} 
?> 
+0

Una mejor respuesta * generalmente * contiene una explicación además del código. ¡Creo que hacerlo mejorará tu respuesta! – amit

1

sólo tiene que utilizar la función de PHP array_key_exists()

<?php 
$search_array = array('first' => 1, 'second' => 4); 
if (array_key_exists('first', $search_array)) { 
    echo "The 'first' element is in the array"; 
} 
?> 
23

Usando:in_array()

$search_array = array('user_from','lucky_draw_id','prize_id'); 

if (in_array('prize_id', $search_array)) { 
    echo "The 'prize_id' element is in the array"; 
} 

Aquí está la salida:The 'prize_id' element is in the array


Usando:array_key_exists()

$search_array = array('user_from','lucky_draw_id','prize_id'); 

if (array_key_exists('prize_id', $search_array)) { 
    echo "The 'prize_id' element is in the array"; 
} 

No hay salida


En conclusión, array_key_exists() no funciona con una simple matriz. Es solo para encontrar si existe una clave de matriz o no. Use in_array() en su lugar.

aquí es más ejemplo:

<?php 
/**++++++++++++++++++++++++++++++++++++++++++++++ 
* 1. example with assoc array using in_array 
* 
* IMPORTANT NOTE: in_array is case-sensitive 
* in_array — Checks if a value exists in an array 
* 
* DOES NOT WORK FOR MULTI-DIMENSIONAL ARRAY 
*++++++++++++++++++++++++++++++++++++++++++++++ 
*/ 
$something = array('a' => 'bla', 'b' => 'omg'); 
if (in_array('omg', $something)) { 
    echo "|1| The 'omg' value found in the assoc array ||"; 
} 

/**++++++++++++++++++++++++++++++++++++++++++++++ 
* 2. example with index array using in_array 
* 
* IMPORTANT NOTE: in_array is case-sensitive 
* in_array — Checks if a value exists in an array 
* 
* DOES NOT WORK FOR MULTI-DIMENSIONAL ARRAY 
*++++++++++++++++++++++++++++++++++++++++++++++ 
*/ 
$something = array('bla', 'omg'); 
if (in_array('omg', $something)) { 
    echo "|2| The 'omg' value found in the index array ||"; 
} 

/**++++++++++++++++++++++++++++++++++++++++++++++ 
* 3. trying with array_search 
* 
* array_search — Searches the array for a given value 
* and returns the corresponding key if successful 
* 
* DOES NOT WORK FOR MULTI-DIMENSIONAL ARRAY 
*++++++++++++++++++++++++++++++++++++++++++++++ 
*/ 
$something = array('a' => 'bla', 'b' => 'omg'); 
if (array_search('bla', $something)) { 
    echo "|3| The 'bla' value found in the assoc array ||"; 
} 

/**++++++++++++++++++++++++++++++++++++++++++++++ 
* 4. trying with isset (fastest ever) 
* 
* isset — Determine if a variable is set and 
* is not NULL 
*++++++++++++++++++++++++++++++++++++++++++++++ 
*/ 
$something = array('a' => 'bla', 'b' => 'omg'); 
if($something['a']=='bla'){ 
    echo "|4| Yeah!! 'bla' found in array ||"; 
} 

/** 
* OUTPUT: 
* |1| The 'omg' element value found in the assoc array || 
* |2| The 'omg' element value found in the index array || 
* |3| The 'bla' element value found in the assoc array || 
* |4| Yeah!! 'bla' found in array || 
*/ 
?> 

Aquí es PHP DEMO

+0

esta debería ser la respuesta. –

+0

¡Respuesta perfecta! –

+0

'array_key_exists()' comprueba las claves de la matriz, mientras que la última '$ search_array' contiene una matriz asociativa. Sin duda no funcionará. Deberías 'array_flip()' primero. – Chay22

2

in_array() está bien si sólo se está comprobando, pero si es necesario comprobar que existe un valor y devolver el asociado clave, array_search es una mejor opción.

$data = array(
    0 => 'hello', 
    1 => 'world' 
); 

$key = array_search('world', $data); 

if ($key) { 
    echo 'Key is ' . $key; 
} else { 
    echo 'Key not found'; 
} 

Esto imprimirá "Key es 1"

0
bool in_array (mixed $needle , array $haystack [, bool $strict = FALSE ]) 

Otro uso de in_array in_array() con una matriz como aguja

<?php 
$a = array(array('p', 'h'), array('p', 'r'), 'o'); 

if (in_array(array('p', 'h'), $a)) { 
    echo "'ph' was found\n"; 
} 

if (in_array(array('f', 'i'), $a)) { 
    echo "'fi' was found\n"; 
} 

if (in_array('o', $a)) { 
    echo "'o' was found\n"; 
} 
?> 
0

Suponiendo que está utilizando una matriz sencilla

. es decir,

$MyArray = array("red","blue","green"); 

Puede utilizar esta función

function val_in_arr($val,$arr){ 
    foreach($arr as $arr_val){ 
    if($arr_val == $val){ 
     return true; 
    } 
    } 
    return false; 
} 

Uso:

val_in_arr("red",$MyArray); //returns true 
val_in_arr("brown",$MyArray); //returns false 
Cuestiones relacionadas