OneBite.Dev - Coding blog in a bite size

Find The Unique Elements In Two Arrays In PHP

Code snippet for how to Find The Unique Elements In Two Arrays In PHP with sample and detail explanation

Here we’ll explore how to identify the unique elements across two arrays using PHP. This functionality is especially useful in situations where you need to compare datasets and identify distinct variables.

Code Snippet

Below is a practical example of how you can find and display the unique elements of two arrays in PHP.

<?php
    // Defining the arrays
    $array1 = array("a", "b", "c", "d");
    $array2 = array("c", "d", "e", "f");
    
    // Merging the arrays
    $array3 = array_merge($array1, $array2);
    
    // Getting the unique values
    $uniqueValues = array_unique($array3);
    
    // Printing the unique values
    print_r($uniqueValues);
?>

Code Explanation

Let’s break this code snippet down, step by step.

  1. Defining the arrays: We’ll start by defining two simple arrays. The first array, $array1, contains the elements “a”, “b”, “c”, and “d”, while the second array, $array2, consists of the elements “c”, “d”, “e”, and “f”.
$array1 = array("a", "b", "c", "d");
$array2 = array("c", "d", "e", "f");
  1. Merging the arrays: In this step, we’re merging both arrays into one using the array_merge() function. This function basically concatenates the arrays in the specified order. The output will be a single array $array3 that contains all the elements from both $array1 and $array2.
$array3 = array_merge($array1, $array2);
  1. Getting the unique values: Afterwards, we’ll need to identify the unique values from the merged array. We’ll use the array_unique() function in PHP for this purpose. This function removes duplicate values from the array, leaving only the unique ones in their original order. The output will be stored in the new array $uniqueValues.
$uniqueValues = array_unique($array3);
  1. Printing the unique values: Finally, we’ll print the unique values using the print_r() function. This will output the unique data elements contained within our two initial arrays.
print_r($uniqueValues);

That’s it! By using the PHP array_merge() and array_unique() functions, it becomes straightforward and efficient to find the unique elements within two arrays. Make sure to test this on your own to get a better understanding of the process.

php