Explain array_diff() in PHP

PHPProgrammingServer Side Programming

PHP offers different kinds of inbuilt functions having particular functionalities. The array_diff() is a predefined function in PHP and is utilized to figure the distinction between at least two arrays. If we utilize this function with two arrays it returns an array containing every element from array1 that are absent in the other arrays.

This function figures the difference between two or more arrays as per the values of the present inside the arrays.


 Live Demo

   $myarray1 = array('c', 'd', 'j', 'k', 'c','d','c');
   $myarray2  = array('j', 'k', 'd');
   print_r(array_diff( $myarray1, $myarray2));


[0] => c
[4] => c
[6] => c


It compares the elements in their string representation. That is, 2 and '2' are both equivalent for array_diff(). The quantity of reiteration of the component in the first array doesn't make a difference. That is if a component happens multiple times in $array1 and just 1 time in a different array then that element will be omitted in the result.

Updated on 29-Jun-2020 09:23:06