PHP remove duplicates from multidimensional array

To php remove duplicates from multidimensional PHP; Through this tutorial, i am going to show you how to remove duplicates from multidimensional array in PHP, remove duplicate elements from array in PHP without using function, PHP remove duplicates from multidimensional array by key.

Remove duplicates from multidimensional array in PHP

Use the below given methods to remove duplicates from multidimensional array in PHP; is as follows:

  • Remove Duplicate values from multidimensional array using function
  • PHP remove duplicates from the multidimensional array by key-value

Remove Duplicate values from multidimensional array using function

Using array_map() and array_unique() function to remove duplicate elements or values from a multidimensional array in PHP; is as follows:

<?php
$arr = Array(
          Array('laravel','php'),
          Array('codeigniter','php'),
          Array('laravel','php'),
          Array('c++','java')
        );
$arr = array_map("unserialize", array_unique(array_map("serialize", $arr)));
print_r($arr);
?>

PHP remove duplicates from the multidimensional array by key-value

Let you have one array look like this:

Array (
    [0] => Array ( [name] => Apple [amount] => 1)
    [1] => Array ( [name] => Apple [amount] => 2)
    [2] => Array ( [name] => Orange [amount] => 3)
    [3] => Array ( [name] => Orange [amount] => 4)
    [4] => Array ( [name] => Banana [amount] => 5)
    [5] => Array ( [name] => Pear [amount] => 6)
)

And want to remove duplicate values/elements from the multi dimensional array by key value; is as follows:

<?php
$orgArray = array( 
    array ('name' => 'Apple', 'amount' => 1),
    array ('name' => 'Apple', 'amount' => 2),
    array ('name' => 'Orange', 'amount' => 3),
    array ('name' => 'Orange', 'amount' => 4),
    array ('name' => 'Banana', 'amount' => 5),
    array ('name' => 'Pear', 'amount' => 6),
);
$newArray = array(); 
$Fruits = array(); 
foreach ( $orgArray AS $key => $line ) { 
    if ( !in_array($line['name'], $Fruits) ) { 
        $Fruits[] = $line['name']; 
        $newArray[$key] = $line; 
    } 
} 
$originalArray = $newArray; 
$newArray = NULL;
$Fruits = NULL;
print_r($orgArray);
?>

Check for duplicate values in a multidimensional array

<?php
  $data = Array(
    0 => Array("a", "b", "c"),
    1 => Array("x", "y", "z"),
    2 => Array("a", "b", "c"),
    3 => Array("a", "b", "c"),
    4 => Array("a", "x", "z"),
);
$final = array();
foreach ($data as $array) {
    if(!in_array($array, $final)){
        $final[] = $array;
    }
}
print_r($final);  
?>

Recommended PHP Tutorials

Be First to Comment

Leave a Reply

Your email address will not be published.