Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Finding same values on multiple array data PHP

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading