Comment vérifier si une valeur de tableau existe?


109

Comment puis-je vérifier si $something['say']a la valeur de 'bla'ou 'omg'?

$something = array('say' => 'bla', 'say' => 'omg');

45
Les clés d'un tableau doivent être uniques.
Gumbo

Réponses:


114

Utilisation if?

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

Btw, vous attribuez une valeur avec la clé saydeux fois, donc votre tableau donnera un tableau avec une seule valeur.


289

Vous pouvez utiliser la fonction PHP in_array

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

7
Est-il possible d'avoir un tableau avec des clés identiques? La deuxième valeur n'écraserait-elle pas l'original?
Citricguy

47

En utilisant: 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";
}

Voici la sortie: The 'prize_id' element is in the array


En utilisant: 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";
}

Pas de sortie


En conclusion, array_key_exists()ne fonctionne pas avec un simple tableau. Il ne s'agit que de savoir si une clé de tableau existe ou non. Utilisez in_array()plutôt.

Voici un autre exemple:

<?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 ||
 */
?>

Voici PHP DEMO


array_key_exists()vérifie les clés du tableau tandis que ce dernier $search_arraycontient un tableau associatif. Nul doute que cela ne fonctionnera pas. Vous devriez le array_flip()faire en premier.
Chay22


6

Pour vérifier si l'index est défini: isset($something['say'])


Je ne comprends pas l'intention de cette réponse. Comment atteindre l'objectif de vérification de la valeur d'un indice?
Brad Koch

Bonne question. Cela ne répond pas du tout à la question, telle qu'elle est écrite. Je ne me souviens pas, mais comme j'ai répondu environ 3 minutes après la question initiale, je suppose que l'OP a modifié sa question originale pour la rendre plus claire, dans le délai de vérification initial avant qu'elle ne soit enregistrée en tant que modification. Si cela a du sens.
écho

5

Vous pouvez tester si un tableau a un certain élément ou pas avec isset () ou parfois même mieux array_key_exists () (la documentation explique les différences). Si vous ne pouvez pas être sûr que le tableau a un élément avec l'index «say», vous devriez d'abord le tester ou vous pourriez recevoir des messages «warning: undefined index ....».

Quant au test pour savoir si la valeur de l'élément est égale à une chaîne, vous pouvez utiliser == ou (encore une fois parfois mieux) l'opérateur d'identité === qui ne permet pas de jongler avec les types .

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

array_key_exists est toujours une meilleure solution
AjayR

5

in_array () convient si vous ne faites que vérifier, mais si vous devez vérifier qu'une valeur existe et renvoyer la clé associée, array_search est une meilleure option.

$data = [
    'hello',
    'world'
];

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

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

Cela affichera "La clé est 1"


3

Utilisez simplement la fonction 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";
}
?>

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

1
Une meilleure réponse contient généralement une explication en plus du code. Je pense que cela améliorera votre réponse!
amit

1

Eh bien, tout d'abord, un tableau associatif ne peut avoir une clé définie qu'une seule fois, donc ce tableau n'existerait jamais. Sinon, utilisez simplement in_array()pour déterminer si cet élément de tableau spécifique est dans un tableau de solutions possibles.


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

Une autre utilisation de in_array in_array () avec un tableau comme aiguille

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

1

En supposant que vous utilisez un tableau simple

. c'est à dire

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

Vous pouvez utiliser cette fonction

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

Usage:

val_in_arr("red",$MyArray); //returns true
val_in_arr("brown",$MyArray); //returns false
En utilisant notre site, vous reconnaissez avoir lu et compris notre politique liée aux cookies et notre politique de confidentialité.
Licensed under cc by-sa 3.0 with attribution required.