0

I have two different arrays like this

 $array1 = [1, 2, 8, 10];
 $array2 = [2, 4, 6, 8, 10, 15, 1];

I want to get the common elements and uncommon elements between them. I almost figured out how to get the common ones as the code below but I can't get uncommon elements.

for($x = 0; $x < count($array1); $x++) {

    for($z = 0; $z < count($array2); $z++) {
            if ( $array1[$x] == $array2[$z] ) {

                $array3 = $array1[$x];
                print_r($array3);

            } elseif ($array1[$x] !== $array2[$z]) {
                // code...
            }

        }
    }

How to get those uncommon or different elements between the two arrays without using a built-in PHP method then output them in a new array.

2
  • Watch php array functions like php.net/manual/en/function.array-intersect.php Commented May 29, 2020 at 22:29
  • I mentioned that I need to know the answer without using any built-in functions or methods Commented May 29, 2020 at 22:33

1 Answer 1

1

You can get the uncommon elements by using in_array() function

<?php
 $array1 = [1, 2, 8, 10];
 $array2 = [2, 4, 6, 8, 10, 15, 1];

  $result = []; 
 for($i = 0;$i < sizeof($array2);$i++){
 if(!in_array($array2[$i],$array1)){
    $result[] =  $array2[$i];
  }
 }
?>

Output

Array
(
    [0] => 4
    [1] => 6
    [2] => 15
)
Sign up to request clarification or add additional context in comments.

2 Comments

what if we cant use in_array method, how to do it?
You can do it by two for loops for both the arrays and set the cindition as if their indexes not intersect fill them in an empty array and later on just print that resultant array

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.