0

I have the following (nested) array:

array(3) { [16]=> array(3) { [0]=> int(159) [1]=> int(160) [2]=> int(158) } 
           [21]=> array(2) { [0]=> int(160) [1]=> int(158) } 
           [19]=> array(2) { [0]=> int(158) [1]=> int(159) } }

As you can see it contains 3 child array's. The child array's all contain the integer '158' as an value but also '159'. I want to somehow loop trough the child array's and do a check if all child array's contain that value. Then I want to return an array with only these values.

I know i could use array_intersect for this however the nested array's are generated dynamically so i'm not sure how to deal with this using array intersect:

<?php
$arr1 = array('158','250','342'); 
$arr2 = array('158','142','352');

$diff1 = array_intersect($arr1, $arr2);
print_r( $diff1 );
//RETURNS Array ( [0] => 158 )
?>
1
  • You want to get common values in all arrays? Commented Oct 23, 2019 at 7:29

2 Answers 2

1

You can use the splat operator(...) to pass all the subarrays into array_intersect() in one go...

$arr1 = [['158','250','342'],['158','142','352'],['1421','158','3521']];

$diff1 = array_intersect(...$arr1);
print_r( $diff1 );
//RETURNS Array ( [0] => 158 )
Sign up to request clarification or add additional context in comments.

1 Comment

This is a much better way to do it these days.
0

After a bit searching around I found the following:

$result = call_user_func_array('array_intersect', $productStoreArray);

As seen on: php dynamic array_intersect

This solves my problem because it returns to me:

//RETURNS Array ( [0] => 158, 1 => 159 )

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.