Remove duplicated elements of associative array in PHP

PHPServer Side ProgrammingProgramming

The ‘array_map’ function sends the value of every element in the array to a user-defined function. It then returns an array with new values, because of calling the user-defined function on the array.

Syntax of array_map function

array_map ( user-defined function, array_1, array_2, array_3…)

The user-defined function and the array_1 are compulsory arguments, but array_2 and array_3 are optional.

Example

 Live Demo

$result = array(
   0=>array('a'=>1,'b'=>'Hello'),
   1=>array('a'=>1,'b'=>'duplicate_val'),
   2=>array('a'=>1,'b'=>'duplicate_val')
);
$unique = array_map("unserialize", array_unique(array_map("serialize", $result)));
print_r($unique);

Output

This will produce the following output −

Array ( [0] => Array ( [a] => 1 [b] => Hello ) [1] => Array ( [a] => 1 [b] => duplicate_val ) )

In the above code, an array is defined with 3 elements and this is assigned to a variable named ‘result’. The array_map function is called and the ‘result’ value is passed as a parameter.

The resultant output would be the contents in the ‘result’ variable along with mention about the duplicate value in the array.

raja
Published on 09-Apr-2020 11:03:57
Advertisements