4

I have two arrays, for example:

array1={1,2,3,4,5,6,7,8,9};
array2={4,6,9}

Is there any function so that I can determine that array2 fully exists in array1?

I know i can use the in_array() function in a loop but in cases where I will have large arrays with hundreds of elements so I am searching for a function.

0

4 Answers 4

11

Try:

$fullyExists = (count($array2) == count(array_intersect($array2, $array1));

The array_intersect.php function will return only elements of the second array that are present in all the other arguments (only the first array in this case). So, if the length of the intersection is equal to the lenght of the second array, the second array is fully contained by the first one.

Sign up to request clarification or add additional context in comments.

Comments

1

You can use array_intersect for this, but you have to be a bit careful.

If the array to match has no duplicates, you can use

// The order of the arrays matters!
$isSubset = count(array_intersect($array2, $array1)) == count($array2);

However this will not work if e.g. $array2 = array(4, 4). If duplicates are an issue, you need to also use array_unique:

$unique = array_unique($array2);
// The order of the arrays matters!
$isSubset = count(array_intersect($unique, $array1)) == count($unique);

The reason that the order of the arrays matters is that the array given as the first parameter to array_intersect must have no duplicates. If the parameters are switched around this requirement will move from $array2 to $array1, which is important as it can change the behavior of the function.

1 Comment

This will force PHP to check for every value to determine if arrays are identical.
0

Quick and easy solution:

 array_diff(array(1,2,3,4,5,6,7,8,9),array(4,6,9));

if the return is a empty array, it is in the array otherwise he'll output the items that aren't

1 Comment

thank you for reply but it is not the correct solution
0

I didn't try with complex array but comparing work for me

var_dump(array(1,2,3,4,5,6,7,8,9) === array(4,6,9));
var_dump(array(1,2,3,4,5,6,7,8,9) === array(1,2,3,4,5,6,7,8,9));

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.