简体   繁体   中英

in_array function is not working

This code should return TRUE value:

<?php
      $return = in_array(array(1, 2), array(1, 2));
?>

but in_array returns FALSE.

in_array checks if a value exists in an array.

Your $needle doens't exists at all as a value of $haystack

that would be ok if your $haystack was

array(1,2,3,array(1,2))

Notice in this case array(1,2) actually is found inside as expected

If you want to check whenever 2 arrays are equal i suggest you the === operator

($a === $b) // TRUE if $a and $b have the same key/value pairs in the same order and of the same types.

Based on your example, you may want to look into array_intersect() . It compares arrays in a fashion that may better align with your spec.

According to the PHP Manual for in_array , the function's syntax is:

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

So you need to supply a $needle value as the first argument. This explains why your example returns FALSE. However, these examples will each return TRUE:

in_array(1, array(1, 2));
in_array(2, array(1, 2));
in_array(array(1, 2), array(1, 2, array(1, 2)))

That said, it might help if you explain exactly what you are trying to do. Perhaps in_array is not the function you need.

Your first array isn't contained in the second array, it's equal.

This returns true:

var_dump(in_array(array(1, 2), array(1, 2, array(1, 2))));

Are you interested in intersection ?

$arr1 = array(1, 2);
$arr2 = array(1, 2);

$return = array_intersect($arr1, $arr2);

if(count($return) === count($arr1)) {
    // all are present in arr2
}

First parameter is the value you're looking for in the second parameter (array) http://php.net/manual/fr/function.in-array.php

you missunderstand in_array see offiziell docs: http://uk.php.net/in_array

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

array(1,2) is not in array(1,2) it is array(1,2),

$return = in_array(array(1, 2), array(array(1, 2)));

would return true. (more an extension of yes123's answer)

In your case, the first parameter of in_array should not be an array, but an integer. What you are doing with that code is checking for the presence of an array inside the array, which is not there. A correct form would be:

in_array(1, array(1, 2)); // true

if second array looks like this

array(array(1, 2));

then return true

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM