2012-01-16 28 views
51

Tengo una variable PHP de tipo Array y me gustaría saber si contiene un valor específico y dejarle saber al usuario que está allí. Este es mi matriz:¿Cómo puedo verificar si una matriz contiene un valor específico en php?

Array ([0] => kitchen [1] => bedroom [2] => living_room [3] => dining_room) 

y me gustaría hacer algo como:

if(Array contains 'kitchen') {echo 'this array contains kitchen';} 

¿Cuál es la mejor manera de hacer lo anterior?

+1

in_array seem best :) También consulte array_key_exists para matrices asociativas. –

+0

posible duplicado de [php - encuentre si una matriz contiene un elemento] (http://stackoverflow.com/questions/3416614/php-find-if-an-array-contains-an-element) – user

Respuesta

114

Uso del in_array() function.

$array = array('kitchen', 'bedroom', 'living_room', 'dining_room'); 

if (in_array('kitchen', $array)) { 
    echo 'this array contains kitchen'; 
} 
+0

Nota: No es Es necesario que todos los elementos de una matriz de PHP sean del mismo tipo de datos. Pueden ser de diferentes tipos de datos. Si quiere hacer coincidir el tipo de datos también, pase 'true' como el tercer argumento de' in_array'. –

+0

cómo hacerlo sin usar la función in_array()? – user2215270

+0

@ user2215270 Puede iterar a través de la matriz con un ['foreach'] (http: // php.net/foreach) u otra estructura de control de bucle, verificando el elemento actual en cada iteración. ¿Pero por qué preferirías hacer eso? – Wiseguy

1
if (in_array('kitchen', $rooms) ... 
8

Ver in_array

<?php 
    $arr = array(0 => "kitchen", 1 => "bedroom", 2 => "living_room", 3 => "dining_room");  
    if (in_array("kitchen", $arr)) 
    { 
     echo sprintf("'kitchen' is in '%s'", implode(', ', $arr)); 
    } 
?> 
12
// Once upon a time there was a farmer 

// He had multiple haystacks 
$haystackOne = range(1, 10); 
$haystackTwo = range(11, 20); 
$haystackThree = range(21, 30); 

// In one of these haystacks he lost a needle 
$needle = rand(1, 30); 

// He wanted to know in what haystack his needle was 
// And so he programmed... 
if (in_array($needle, $haystackOne)) { 
    echo "The needle is in haystack one"; 
} elseif (in_array($needle, $haystackTwo)) { 
    echo "The needle is in haystack two"; 
} elseif (in_array($needle, $haystackThree)) { 
    echo "The needle is in haystack three"; 
} 

// The farmer now knew where to find his needle 
// And he lived happily ever after 
0

Usando variable dinámica para la búsqueda en orden

/* https://ideone.com/Pfb0Ou */ 

$array = array('kitchen', 'bedroom', 'living_room', 'dining_room'); 

/* variable search */ 
$search = 'living_room'; 

if (in_array($search, $array)) { 
    echo "this array contains $search"; 
} else 
    echo "this array NOT contains $search"; 
0

A continuación se presenta cómo se puede hacer esto:

<?php 
$rooms = ['kitchen', 'bedroom', 'living_room', 'dining_room']; # this is your array 
if(in_array('kitchen', $rooms)){ 
    echo 'this array contains kitchen'; 
} 

Asegúrese de que la búsqueda de cocina y no Cocina. Esta función es sensible a mayúsculas y minúsculas Por lo tanto, la función a continuación, simplemente no funcionará:

$rooms = ['kitchen', 'bedroom', 'living_room', 'dining_room']; # this is your array 
if(in_array('KITCHEN', $rooms)){ 
    echo 'this array contains kitchen'; 
} 

Si bien desea una forma rápida de hacer que esta consulta sea insensible , echar un vistazo a la solución propuesta en esta respuesta: https://stackoverflow.com/a/30555568/8661779

Fuente: http://dwellupper.io/post/50/understanding-php-in-array-function-with-examples

Cuestiones relacionadas