How to Compare Two or More Array Values in PHP

How to Compare Two or More Array Values in PHP - Lara Tutorials

Answer: Using array_diff() function

We can compare the array elements using the array_diff() function. This function compares the array elements of two or more arrays and returns the difference. The returned value is the element that is present in the first array but not present in the remaining arrays with which we are comparing the first array.

Example: Comparing two array elements

In the given example, we have compared the values of two arrays $arr1 and $arr2 using array_diff() function.

<!DOCTYPE html>  
<html> 
<head>
	<title>Compare two array values</title>
</head> 
<body>  
	<?php
		$arr1 = array("red", "blue", "green", "pink"); 
		$arr2 = array("blue", "pink", "red", "yellow");
		$comp_arr = array_diff($arr1, $arr2);
		print_r($comp_arr);
	?>
</body>  
</html>  

Output:

Array ( [2] => green )

Using array_intersect() function

We can also compare the values of two or more arrays using the array_intersect() function. This function compares the values of two or more arrays and returns an array with the values of the first array that are also present in all other arrays.

Example: Comparing two arrays

In the given example, we have compared the values of two arrays using the $arr1 and $arr2 using the array_intersect() function.

<!DOCTYPE html>  
<html> 
<head>
	<title>Compare two array values</title>
</head> 
<body>  
	<?php
		$arr1 = array("red", "blue", "green", "pink"); 
		$arr2 = array("blue", "pink", "red", "yellow");
		$comp_arr = array_intersect($arr1, $arr2);
		print_r($comp_arr);
	?>
</body>  
</html>  

Output:

Array ( [0] => red [1] => blue [3] => pink )

Conclusion

In this lesson, we have learned how to compare two array values in PHP. Here we have compared the values of two or more arrays using two built-in functions in PHP. First, we have used the array_diff() function. This function compares the values of two or more arrays and returns the values of the first arrays, which are not present in the remaining arrays. Then we have compared the arrays using the array_intersect() function. This function returns the values of the first array, which is present in the remaining arrays.

Leave a Reply

Your email address will not be published.