J'ai le tableau suivant:
$tab[0] = array(1, 2, 3);
$tab[1] = array(3, 4, 5);
$tab[3] = array(6, 7, 8);
Est-il possible d'utiliser in_array pour savoir si une valeur se trouve dans l'un des sous tableaux?Merci pour vos réponses.
$tab[0] = array(1, 2, 3);
$tab[1] = array(3, 4, 5);
$tab[3] = array(6, 7, 8);
Est-il possible d'utiliser in_array pour savoir si une valeur se trouve dans l'un des sous tableaux?$tab[0] = array(1, 2, 3);
$tab[1] = array(3, 4, 5);
$tab[3] = array(6, 7, 8);
$tst = 3;
echo (int)in_array($tst, array_merge($tab[0], $tab[1], $tab[3])); // 1
/* ----- */
$tst = 12;
echo (int)in_array($tst, array_merge($tab[0], $tab[1], $tab[3])); // 0
$tab[0] = array(1, 2, 3);
$tab[1] = array(3, 4, 5);
$tab[3] = array(6, 7, 8);
$tst = 3;
$res = 0;
function inArray($arr, $key) {
global $tst, $res;
if (in_array($tst, $arr)) { $res = 1; }
}
array_walk($tab, 'inArray');
echo $res; // 1
/* ----- */
$tst = 12;
echo $res; // 0
$tab[0] = array(1, 2, 3);
$tab[1] = array(3, 4, 5);
$tab[3] = array(6, 7, 8);
$tst = 3;
$res = 0;
foreach ($tab as $key => $val) {
if (in_array($tst, $val)) { $res = 1; }
}
echo $res; // 1
/* ----- */
$tst = 12;
echo $res; // 0
Ces codes peuvent bien-sûr être optimisés le cas échéant...
Tel que tu le demande la réponse est non. On ne peut pas passer de praramètre à in_array() pour lui indiquer de chercher sur plusieurs niveaux. Comme l'indique la doc http://fr2.php.net/in_array in_array — Indique si une valeur appartient à un tableau (que cette valeur soit elle-même un tableau ou non)oui effectivement, ça marche bien. mais vu que in_array a un foreach "intégré" pour parcourir un tableau, je me demande si c'est possible de faire la même chose sur les sous tableaux: ne pas utiliser de foreach.