How to Compare Two or More Array Values in PHP

Compare two ormore array value or array elements in PHP; Through this tutorial, i am going to show you how to compare two or more array values or array elements in PHP.

How to Compare Two or More Array Values in PHP

Using the PHP array_diff() function compares the values of two or more arrays values. And returns a new array with unique values.

Now, i will take following examples using array_diff() function in php to compare two or more array values or elements of arrays in PHP; is as follows:

  • Example 1 – Compare two arrays in PHP
  • Example 2 – Compare Numeric Array in PHP
  • Example 3 – Compare Three Arrays in PHP

Example 1 – Compare two arrays in PHP

Let you have two arrays with duplicate values in php. And want to remove the duplicate values from these arrays and create a new unique array in PHP; so you can use the following example using array_diff() in php; is as follows:

    <?php
    $array_one = array("first", "second", "third", "fourth", "five");
    $array_second = array("first", "second", "third", "fourth");

    $res = array_diff($array_one,$array_second);

    print_r($res);
    ?>

Example 2 – Compare Numeric Array in PHP

Let you have two numeric arrays with duplicate values. And we will remove the duplicate values from these arrays and create a new unique array in PHP: ; so you can use the following example using array_diff() in php; is as follows:

    <?php
    $array_one = array(1, 2, 3, 4, 5, 6);
    $array_second = array(1, 2, 3, 4);

    $res = array_diff($array_one,$array_second);

    print_r($res);
    ?>

Example 3 – Compare Three Arrays in PHP

Let you have more than two arrays with duplicate values. And we will remove the duplicate values from these arrays and create a new unique array in PHP: ; so you can use the following example using array_diff() in php; is as follows:

    <?php

    $array1 = array('a', 'b', 'c', 'd', 'e', 'f'); 

    $array2 = array('a', 'b', 'g', 'h'); 
    
    $array3 = array('a', 'f', 'i'); 

    $res = array_diff($array1, $array2, $array3);

    print_r($res);
    ?>

Recommended PHP Tutorials

Be First to Comment

Leave a Reply

Your email address will not be published.