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
46

Comments

to add a comment.

Other publications

Automatic setting of the user's time zone
date_default_timezone_set sets the default timezone used by all date / time functions.
126
0
Serialize function, possible problems
The serialize () function returns a string representation of any value (array, object, etc.). Using serialize on an...
47
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.
134
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
78
0
Session lifetime in PHP
By default, in php, the session lifetime is only 24 minutes, and cookies are saved until the browser is closed, such parameters are set on many hosting services.
362
0
Writing and reading files in PHP
Examples of saving and reading text data and arrays to files.
179
0