1

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.

6
  • 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? Commented Jan 10, 2022 at 15:44
  • 2
    Check php.net/manual/fr/function.array-intersect.php Commented Jan 10, 2022 at 15:44
  • 1
    I think like this print_r(array_intersect($arr1, $arr2, $arr3, $arr4)); Commented Jan 10, 2022 at 15:45
  • 1
    Thanks @executable and The fourth bird it's work! Commented Jan 10, 2022 at 15:54
  • 1
    Does this answer your question? Find common values in multiple arrays with PHP Commented Jan 11, 2022 at 14:37

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

5 Comments

Why don't use the php function array_intersect ?
Check my second option :)
I use the second option :) thanks! @Timberman
@behzadmsalehi why wouldnt it work then? Then you will still get the response you want?
@Timberman yes you are right, I make a mistake, sorry.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.