Php does array contain array

How do I check if an array contains values from another array?

I have 2 arrays, each of them var_dump() ‘ed below. I’ve tried with array_intersect() , but nothing is returned, and no errors:

if (array_intersect($userInterests, $interests))
array(3) < [0]=>object(stdClass)#8 (1) < ["interestId"]=>string(1) "2" > [1]=> object(stdClass)#6 (1) < ["interestId"]=>string(1) "3" > [2]=> object(stdClass)#9 (1) < ["interestId"]=>string(1) "5" > > 
array(15) < [0]=>object(stdClass)#2 (2) < ["interestName"]=>string(5) "Musik" ["interestID"]=> string(1) "1" > [1]=> object(stdClass)#11 (2) < ["interestName"]=>string(3) "Mad" ["interestID"]=> string(1) "2" > [2]=> object(stdClass)#12 (2) < ["interestName"]=>string(6) "Rejser" ["interestID"]=> string(1) "3" > [3]=> object(stdClass)#13 (2) < ["interestName"]=>string(10) "Mad Moneyz" ["interestID"]=> string(1) "4" > [4]=> object(stdClass)#14 (2) < ["interestName"]=>string(5) "Biler" ["interestID"]=> string(1) "5" > [5]=> object(stdClass)#15 (2) < ["interestName"]=>string(7) "Netflix" ["interestID"]=> string(1) "6" > [6]=> object(stdClass)#16 (2) < ["interestName"]=>string(26) "Lange gåture på stranden" ["interestID"]=> string(1) "7" > [7]=> object(stdClass)#17 (2) < ["interestName"]=>string(15) "Bjergbestigning" ["interestID"]=> string(1) "8" > > 
 

$interest is the specific interest taken out from the bigger array, $interests $userInterests is the smaller array

Источник

in_array

Searches for needle in haystack using loose comparison unless strict is set.

Parameters

Note:

If needle is a string, the comparison is done in a case-sensitive manner.

If the third parameter strict is set to true then the in_array() function will also check the types of the needle in the haystack .

Note:

Prior to PHP 8.0.0, a string needle will match an array value of 0 in non-strict mode, and vice versa. That may lead to undesireable results. Similar edge cases exist for other types, as well. If not absolutely certain of the types of values involved, always use the strict flag to avoid unexpected behavior.

Return Values

Returns true if needle is found in the array, false otherwise.

Examples

Example #1 in_array() example

$os = array( «Mac» , «NT» , «Irix» , «Linux» );
if ( in_array ( «Irix» , $os )) echo «Got Irix» ;
>
if ( in_array ( «mac» , $os )) echo «Got mac» ;
>
?>

The second condition fails because in_array() is case-sensitive, so the program above will display:

Example #2 in_array() with strict example

if ( in_array ( ‘12.4’ , $a , true )) echo «‘12.4’ found with strict check\n» ;
>

if ( in_array ( 1.13 , $a , true )) echo «1.13 found with strict check\n» ;
>
?>

The above example will output:

1.13 found with strict check

Example #3 in_array() with an array as needle

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» ;
>
?>

The above example will output:

See Also

  • array_search() — Searches the array for a given value and returns the first corresponding key if successful
  • isset() — Determine if a variable is declared and is different than null
  • array_key_exists() — Checks if the given key or index exists in the array

User Contributed Notes 8 notes

Loose checking returns some crazy, counter-intuitive results when used with certain arrays. It is completely correct behaviour, due to PHP’s leniency on variable types, but in «real-life» is almost useless.

The solution is to use the strict checking option.

$array = array(
‘egg’ => true ,
‘cheese’ => false ,
‘hair’ => 765 ,
‘goblins’ => null ,
‘ogres’ => ‘no ogres allowed in this array’
);

// Loose checking — return values are in comments

// First three make sense, last four do not

in_array ( null , $array ); // true
in_array ( false , $array ); // true
in_array ( 765 , $array ); // true
in_array ( 763 , $array ); // true
in_array ( ‘egg’ , $array ); // true
in_array ( ‘hhh’ , $array ); // true
in_array (array(), $array ); // true

in_array ( null , $array , true ); // true
in_array ( false , $array , true ); // true
in_array ( 765 , $array , true ); // true
in_array ( 763 , $array , true ); // false
in_array ( ‘egg’ , $array , true ); // false
in_array ( ‘hhh’ , $array , true ); // false
in_array (array(), $array , true ); // false

I got an unexpected behavior working with in_array. I’m using following code:

// .
$someId = getSomeId (); // it gets generated/fetched by another service, so I don’t know what value it will have. P.S.: it’s an integer

// The actual data in my edge-case scenario:
// $someId = 0;
// $anyArray = [‘dataOne’, ‘dataTwo’];
if ( in_array ( $someId , $anyArray )) // do some work
>
// .
?>

With PHP7.4, in_array returns boolean true.
With PHP8.1, in_array returns boolean false.

It took me quite some time to find out what’s going on.

I found out that in_array will *not* find an associative array within a haystack of associative arrays in strict mode if the keys were not generated in the *same order*:

$needle = array(
‘fruit’ => ‘banana’ , ‘vegetable’ => ‘carrot’
);

$haystack = array(
array( ‘vegetable’ => ‘carrot’ , ‘fruit’ => ‘banana’ ),
array( ‘fruit’ => ‘apple’ , ‘vegetable’ => ‘celery’ )
);

echo in_array ( $needle , $haystack , true ) ? ‘true’ : ‘false’ ;
// Output is ‘false’

echo in_array ( $needle , $haystack ) ? ‘true’ : ‘false’ ;
// Output is ‘true’

?>

I had wrongly assumed the order of the items in an associative array were irrelevant, regardless of whether ‘strict’ is TRUE or FALSE: The order is irrelevant *only* if not in strict mode.

I’d like to point out that, if you’re using Enum data structures and want to compare whether an array of strings has a certain string Enum in it, you need to cast it to a string.

From what I’ve tested, the function works correctly:
if the array is filled with strings and you’re searching for a string;
if the array is filled with Enums and you’re searching for an Enum.

Here is a recursive in_array function:

$myNumbers = [
[ 1 , 2 , 3 , 4 , 5 ],
[ 6 , 7 , 8 , 9 , 10 ],
];

$array = [
‘numbers’ => $myNumbers
];

// Let’s try to find number 7 within $array
$hasNumber = in_array ( 7 , $array , true ); // bool(false)
$hasNumber = in_array_recursive ( 7 , $array , true ); // bool(true)

function in_array_recursive ( mixed $needle , array $haystack , bool $strict ): bool
foreach ( $haystack as $element ) if ( $element === $needle ) return true ;
>

$isFound = false ;
if ( is_array ( $element )) $isFound = in_array_recursive ( $needle , $element , $strict );
>

if ( $isFound === true ) return true ;
>
>

If you’re creating an array yourself and then using in_array to search it, consider setting the keys of the array and using isset instead since it’s much faster.

$slow = array( ‘apple’ , ‘banana’ , ‘orange’ );

if ( in_array ( ‘banana’ , $slow ))
print( ‘Found it!’ );

$fast = array( ‘apple’ => ‘apple’ , ‘banana’ => ‘banana’ , ‘orange’ => ‘orange’ );

if (isset( $fast [ ‘banana’ ]))
print( ‘Found it!’ );

Источник

PHP: Check if an array contains all array values from another array

I would like to find out if $all contains all $search_this values and return true or false . Any ideas please?

@VishalKumarSahu Not quite a duplicate: Your given link has to do with checking if ANY elements are contained in another array, not if ALL elements are contained in another.

6 Answers 6

The previous answers are all doing more work than they need to. Just use array_diff. This is the simplest way to do it:

$containsAllValues = !array_diff($search_this, $all); 

! operator on array will always return true. Use @Miguel ‘s suggestion: empty(array_diff($search_this, $all));

The original answer works because an empty array evaluates as false in PHP. Using empty() also works, but the ! operator does work fine.

This should actually be flipped, so it reads $containsAllValues = !array_diff($all, $search_this); —— Example: $containsAllValues = !array_diff($all = [‘a’, ‘b’, ‘c’], $search_this = [‘c’, ‘c’, ‘c’]); >> result false —— Example: $containsAllValues = !array_diff($search_this = [‘c’, ‘c’, ‘c’], $search_this = [‘a’, ‘b’, ‘c’]); >> Result true

$containsSearch = count(array_intersect($search_this, $all)) === count($search_this); 

Or for associative array, look at array_intersect_assoc().

Or for recursive compare of sub-arrays, try:

 $value) < if (!static::intersectsDeep($value, $actual[$key])) < return false; >> return true; > elseif (is_array($expected) || is_array($actual)) < return false; >return (string) $expected == (string) $actual; > > 

@Wrikken Can’t the values get reordered during array_intersect() ? I mean, [‘a’, ‘b’] != [‘b’, ‘a’] .

@exizt: array_intersect() does not alter the input arrays, so $search_this & $all are safe (it just returns an output). The function signature is array array_intersect ( array $array1 , array $array2 [, array $. ] ) (safe). If it would/could alter them, it would be array array_intersect ( array &$array1 , array &$array2 [, array &$. ] ) (possible altering of input arguments). Also, the keys of $search_this are preserve, and the order of the first array is kept. So, both key/value pairs, as their order, match.

And even then: array comparison: » == TRUE if $a and $b have the same key/value pairs.», so the order doesn’t even matter (use === for that)

This answer assumes that the $all array only contains unique values. If this is not the case, one may use the array_unique function on the $all array in the array_intersects function.

$musthave = array('a','b'); $test1 = array('a','b','c'); $test2 = array('a','c'); $containsAllNeeded = 0 == count(array_diff($musthave, $test1)); // this is TRUE $containsAllNeeded = 0 == count(array_diff($musthave, $test2)); // this is FALSE 

I think you’re looking for the intersect function

array array_intersect ( array $array1 , array $array2 [, array $ . ] ) 

array_intersect() returns an array containing all values of array1 that are present in all the arguments. Note that keys are preserved.

function array_keys_exist($searchForKeys = array(), $searchableArray)

The other answers work with the given use case, however, you might get a false positive if you’re checking » [] exists in $all «. One way you can account for this edge case using array_diff() is like so:

function hasAllElems(array $arr1, array $arr2): bool < if (empty($arr1) && ! empty($arr2)) < return false; >return ! array_diff($arr1, $arr2); > $searchThis = [0 => 200, 1 => 234]; $all = [0 => 307, 1 => 157, 2 => 234, 3 => 200, 4 => 322, 5 => 324]; var_dump(hasAllElems($searchThis, $all)); // true var_dump(hasAllElems($all, $searchThis)); // false var_dump(hasAllElems([], $all)); // false var_dump(hasAllElems($searchThis, [])); // false 

Here, by making an explicit check (i.e. if first array is empty and the second array is not empty), you can return false early in the code.

You can, of course, also use array_intersect() or a loop to achieve the same.

Wrote a blog post for those interested in learning more.

Источник

How to check if an array contains another array in PHP?

How is it actually possible to find out if array «a» has an array element in it and return the key if there is one (or more)?

I would probably loop through it and test with is_array — capture the key, and return the keys when you’re done

3 Answers 3

function look_for_array(array $test_var) < foreach ($test_var as $key =>$el) < if (is_array($el)) < return $key; >> return null; > 

It’s rather trivial to convert this function into collecting all such keys:

function look_for_all_arrays(array $test_var) < $keys = []; foreach ($test_var as $key =>$el) < if (is_array($el)) < $keys[] = $key; >> return $keys; > 

Yes, I’ve tried the same, but this way, I will receive Warning: Invalid argument supplied for foreach() , because it’s in the wrong format for the array one. I know I can just ignore it with @ but is there any other way around it?

Note that array typehint in the function’s parameter. If you’re not sure whether or not $test_var is an array, you should check it as well (with is_array ) — but that probably means something else is wrong in your code.

Thank you I’ve found the issue in my code. The problem was that I’ve typed wrong some elements in the array actually. Thank you for the answer, I must by very tired that I’ve checked it multiple times and didn’t see an error.

 $array = array(1 => 5, 2 => 3, 3 => 13, 9 => array('test'), 4 => 32, 5 => 33); foreach($array as $key => $value) < if(is_Array($value))< echo $valuePhp does array contain array; >> 

I have tried in different way.

$a = array(1 => 5, 2 => 3, 3 => 13, 9 => array('test'), 4 => 32, 5 => 33); foreach ( $a as $aas ): if(is_array($aas)) < foreach ($aas as $key =>$value): echo " (child array is this $key : $value)"; endforeach; >else < echo " Value of array a = $aas : "; >endforeach; 
 Value of array a = 5 : Value of array a = 3 : Value of array a = 13 : (child array is this 0 : test) Value of array a = 32 : Value of array a = 33 : 

Источник

Читайте также:  Shutdown hook in java
Оцените статью