It is necessary to compare several arrays for matching values.

$result = array_intersect($var_1,$var_2,$var_3,$var_4,$var_5,$var_6,$var_7); 

If there is an array, then we transfer it, if not, then we compare the others for each of them. If there is no $var_2 , but there are others, then compare it with $result = array_intersect($var_1,$var_3,$var_4,$var_5,$var_6,$var_7); if there is no $var_5,$var_6 , but there are others, then compare it as $result = array_intersect($var_1,$var_2,$var_3,$var_4,$var_7); And so on.

  • “If not” - even the variable $var_N not defined? - Sergiks
  • Only $var_1 always exists. - Torawhite

3 answers 3

  1. call_user_func_array() - calls a function with an array of parameters.
  2. array_filter() filters an array.

The plan is this: from the array of arrays we leave only non-empty elements, and pass them to array_intersect() :

 $result = call_user_func_array( 'array_intersect', array_filter( array( $var_1,$var_2,$var_3,$var_4,$var_5,$var_6,$var_7 ), function($a){ return isset($a) && is_array($a) && !!count($a);} ) ); 

Working example

  • Thank! Exactly what is needed. Works! - Torawhite

Collect all the var_N that you want to compare into one array list and pass to array_intersect via call_user_func_array

 call_user_func_array('array_intersect', $array_of_var_N); 
  • Multidimensional array? That is, I create the key [0] and write the array var_1 , [1] and write the array var_2 - right? - Torawhite

You can do the following - compare the arrays in pairs in a loop, after clearing the array list of null values ​​and empty arrays:

 // Функция фильтрации пустых и несуществующих массивов function not_empty_arr(...$arrs) { $results = []; foreach($arrs as $arr) { if(isset($arr) && !empty($arr)) { $results[] = $arr; } } return $results; } // Функция получения пересечения элементов массива function arr_intersect($arrs) { $result = $arrs[0]; foreach($arrs as $arr) { $result = array_intersect($result, $arr); } return $result; } $fst = [1, 2, 3, 4, 5]; $snd = [2, 3, 4, 5, 6]; $thd = [3, 4, 5, 6, 7]; $fth = []; $result = arr_intersect( not_empty_arr( null, isset($hello) ? $hello : null, isset($fst) ? $fst : null, isset($fth) ? $fth : null, isset($thd) ? $thd : null, isset($snd) ? $snd : null )); echo '<pre>'; print_r($result); 
  • $arrs - array in which to place all 7 arrays, regardless of its existence? - Torawhite
  • In this case, the arrays are $ fst, $ snd, $ thd, $ fth, and $ arrs is filled inside the not_empty_arr () and arr_intersect () functions. - cheops