This question already has an answer here:
i need help on filtering my 2 dimensional array such as example below:
array(29) {
[0]=> array(2) {
[0]=> string(16) "Andorra La Vella"
[1]=> string(2) "AD"
}
[1]=> array(2) {
[0]=> string(16) "Andorra La Vella"
[1]=> string(2) "AD"
}
[2]=> array(2) {
[0]=> string(16) "Andorra La Vella"
[1]=> string(2) "AD"
}
[3]=> array(2) {
[0]=> string(16) "Andorra La Vella"
[1]=> string(2) "AD"
}
[4]=> array(2) {
[0]=> string(12) "Les Escaldes"
[1]=> string(2) "AD"
}...
how do i filter any redundant value from my array? such as key[0] has the same value as key[1][2][3] and i want to remove this redundant value from my array.
i tried array_filter()
but no luck. i tried array_splice()
and unset()
, no luck in either one.
does php provides any native array function for this?
thanks,
aji
</div>
Can array_unique()
do this? Not sure if it works with nested arrays.
EDIT: no, it can't do it.
Note: Note that array_unique() is not intended to work on multi dimensional arrays.
If you want to remove duplicates you can find some more info on another thread
Enjoy!
$to_filter = array(); // your array
$filtered = array(); // unique values
array_walk($to_filter, function($v, $k) use (&$filtered) {
if(!in_array($v, $filtered)) {
$filtered[] = $v;
}
});
And how clean it looks with PHP 5.3's anonymous functions..,.