ADVERTISEMENTS

How to compare two array values in PHP

PHP provides a variety of built-in functions for array. For getting difference between two arrays we use the array_diff() function which is used to compare two or more arrays and return the values from the first array that are not present in any of the other arrays. The returned array will contain only the elements from the first array that are not present in any of the other arrays. The function takes in the arrays as parameters and returns the resulting array.

The following example will explain you that the function compares the values of the arrays $array1, $array2, $array3 and returns an array that contains only the elements from $array1 that are not present in $array2 and $array3.

<?php
$array1 = array("a" => "red", "b" => "green", "c" => "blue", "d" => "yellow");
$array2 = array("e" => "red", "f" => "black", "g" => "purple");
$array3 = array("a" => "red", "b" => "black", "h" => "yellow");

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

print_r($result);
?>

 

PHP (Hypertext Preprocessor) is a server-side scripting language used to create web pages and web applications. It can be embedded into HTML and is often used in combination with databases such as MySQL to create dynamic, interactive websites. You can learn php from our PHP Tutorials and PHP Examples

ADVERTISEMENTS