0

I got this case. I want to return same value that contain from all array data.

$arr1 = [1,2,3,4,5,9,14];
$arr2 = [1,2,10];
$arr3 = [1,2,5];
$arr4 = [1,2,3,5];

The return array value after filtering should :

$finalArr = [1, 2];

Why 1, 2? Because it's contain in all array data. Then how to filter between array data and to finding final array in PHP? Thanks in advance.

Ardan
  • 23
  • 5
  • 1
    There is nothing wrong with asking for a bit of help with your homework. Beginners are welcome, but we expect a good faith attempt at an answer from you first. ___SO is not a free coding service___ although we are very willing to help you fix issues with code you have written. [How do I ask and answer homework questions?](https://meta.stackoverflow.com/questions/334822/how-do-i-ask-and-answer-homework-questions) – RiggsFolly Jan 10 '22 at 15:44
  • 2
    Check https://www.php.net/manual/fr/function.array-intersect.php – executable Jan 10 '22 at 15:44
  • 1
    I think like this `print_r(array_intersect($arr1, $arr2, $arr3, $arr4));` – The fourth bird Jan 10 '22 at 15:45
  • @RiggsFolly It's not a homework. A website project. 1, 2 is a data_id. – Ardan Jan 10 '22 at 15:48
  • 1
    Thanks @executable and The fourth bird it's work! – Ardan Jan 10 '22 at 15:54
  • 1
    Does this answer your question? [Find common values in multiple arrays with PHP](https://stackoverflow.com/questions/5299608/find-common-values-in-multiple-arrays-with-php) – Hendrik Jan 11 '22 at 14:37

1 Answers1

2

This works!

$arr1 = [1,2,3,4,5,9,14];
$arr2 = [1,2,10];
$arr3 = [1,2,5];
$arr4 = [1,2,3,5];


$duplicates = checkduplicate($arr1, $arr2, $arr3, $arr4);

print_r($duplicates);

function checkduplicate($arr1, $arr2, $arr3, $arr4)
{
    $keys = [];
    foreach($arr1 as $key)
    {
        if(in_array($key, $arr2) && in_array($key, $arr3) && in_array($key, $arr4))
        {
            $keys[] = $key;
        }
    }

    return $keys;
}

This iterates over all the items in the first array, and check if they also contain in the others

You can also use array intersect, which takes multiple arrays

$duplicates = array_intersect($arr1, $arr2, $arr3, $arr4);
Timberman
  • 647
  • 8
  • 24