There are two arrays. It is necessary to leave with the first array only those elements that are found in the second. As you know, you can do this with in_array inside foreach :

 $firstArray = array('A','B','C','D','E'); $secondArray = array('A','C','E','X','Y','Z'); $arrayOfResults = array(); foreach($firstArray as $item) { if(in_array($arrayOfAllItems, $secondArray )) { $arrayOfResults[] = $item; } } echo implode(',',$arrayOfResults); // A, C, E 

But how can I get $arrayOfResults without using foreach() ? For example via array_map() or something else?

  • Just curious, and what you did not please foreach ? - Dmitriy Simushev
  • If you already have an array of elements SELECTED among the elements of the first array, why do you need another such array - essentially a copy of it? Some kind of nonsense. - hindmost
  • In the second array there are elements that are not in the first. It is necessary to leave with the first only those contained in the second. Updated the question to make it clearer - stckvrw
  • 3
    @stckvrw php.net/manual/ru/function.array-intersect.php help? array_intersect - Computes the convergence of arrays ...... Returns an array containing all the values ​​of array1 that exist in all passed arguments. - Alexey Shimansky
  • Yes, what you need, thanks! - stckvrw

1 answer 1

PHP has a search function for converging arrays: array_intersect

 $arr1 = array(...); $arr2 = array(...); $arr1 = array_intersect($arr1, $arr2); 

As a result, the first array is left to itself only those elements that exist in the second, and in the first arrays.