Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

php

What is the array_diff() function in PHP?

NDUKWE CHIDERA K.

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Overview

The array_diff() function is a built-in method in PHP that requires PHP version 4.0.1 and later. This function finds the difference between an array and the number of other arrays.

It checks in a $A array and tries to find the values in $A that are not in different arrays like $B, $C, and so on. The found values return in an array.

Simply put, if provided $A = [5,6,7] as the first array, and the arrays $B = [5,8,6] and $C = [7,11,10], the array_diff() function returns the value [6] which is found in $A but not in $B or $C.

Syntax

array_diff($mainArray, $array1...$arrayn)

Parameters

  • $mainArray: This is the array whose values will be checked for in others.
  • $array1,...$arrayn: These are any numbers of arrays that will be searched to find any value from the $mainArray.

Return values

This method returns the difference between the content of $mainArray and the other arrays as an array.

Code

The code snippet shows a sample use of the array_diff() method to return the difference between some arrays.

<?php
$A = [5,6,7];
$B = [5,8,7];
$C = [7 ,11, 10];
//Obtaining the difference between array A and the others
print_r(array_diff($A,$B,$C));
$firstArray = array("gin", "y"=> "skin", "clothe", "family", "home","bin");
$secondArray = ["bin" , "x"=> "food", "skin", "family","dance"];
//Checking for and returning the contents in $firstArray that are not in $secondArray
$output = array_diff($firstArray, $secondArray);
print_r($output);
?>

Explanation

  • Lines 2–4: We declare some array values to be used later in the code.
  • Line 7: We get the array_diff() function's outcome for the three arrays declared earlier.
  • Lines 10–11: We declare some more arrays with values.
  • Line 14: We check for the contents in $firstArray that are not in $secondArray using the array_diff() method, and return the output.
  • Line 16: We display the returned array using the print_r method.

RELATED TAGS

php

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring