array_unique for multidimensional arrays

array_unique for multidimensional arrays

$ unique = array_unique ($ array);

The array_unique function returns an array without duplicate values, and it works with multidimensional arrays as well. You can clear the arrays from duplicates in the following ways:

Method #1

$array = array_unique($array, SORT_REGULAR);
PHP

Method #2

$array = array_map('unserialize', array_unique(array_map('serialize', $array)));
PHP

The second way is data type sensitive, i.e. 0 => 1, and 0 => '1', will be considered different.

Remove duplicates one key at a time

function array_unique_key($array, $key) { 
	$tmp = $key_array = array(); 
	$i = 0; 

	foreach($array as $val) { 
		if (!in_array($val[$key], $key_array)) { 
			$key_array[$i] = $val[$key]; 
			$tmp[$i] = $val; 
		} 
		$i++; 
	} 
	return $tmp; 
}
PHP

For example, in an array, you need to remove duplicates with the same id, other elements of the array are not important.

$test = array( 
	array(
		'id' => 1,
		'name' => 'Sparco wheels',
		'price' => 5000,
	),
	array(
		'id' => 1,
		'name' => 'Sparco wheels',
		'price' => 6000,
	), 	
	array(
		'id' => 2,
		'name' => 'Car seat',
		'price' => 3000,
	), 

);

$test = array_unique_key($test, 'id'); 
print_r($test);
PHP

Result:

Array(
	[0] => Array(
		[id] => 1
		[name] => Sparco wheels
		[price] => 5000
	)
	[2] => Array(
		[id] => 2
		[name] => Car seat
		[price] => 3000
	)
)
28.06.2019, updated 27.05.2021
29

Comments

to add a comment.

Other publications

Checking data with regular expressions
A collection of regular expressions with examples in PHP for validating data from form fields.
49
0
Automatic setting of the user's time zone
date_default_timezone_set sets the default timezone used by all date / time functions.
112
0
Serialize function, possible problems
The serialize () function returns a string representation of any value (array, object, etc.). Using serialize on an...
31
0
Examples of using cURL in PHP
cURL PHP is a library for receiving and transmitting data via protocols such as HTTP, FTP, HTTPS. The library is used...
316
0
How to set up Last-Modified
The Last-Modified header helps to optimize the loading of web pages and make the job easier for search engines.
97
0
How to find out if a request came via AJAX
To distinguish between direct and AJAX requests, simply check the value of the $ _SERVER global variable
60
0