Remove duplicated elements of associative array in PHP - php

$result = array(
0=>array('a'=>1,'b'=>'Hello'),
1=>array('a'=>1,'b'=>'other'),
2=>array('a'=>1,'b'=>'other'),
);
If it is duplicated removed it, so the result is as follows:
$result = array(
0=>array('a'=>1,'b'=>'Hello'),
1=>array('a'=>1,'b'=>'other')
);
Could any know to do this?
Thanks

Regardless what others are offering here, you are looking for a function called array_uniqueDocs. The important thing here is to set the second parameter to SORT_REGULAR and then the job is easy:
array_unique($result, SORT_REGULAR);
The meaning of the SORT_REGULAR flag is:
compare items normally (don't change types)
And that is what you want. You want to compare arraysDocs here and do not change their type to string (which would have been the default if the parameter is not set).
array_unique does a strict comparison (=== in PHP), for arrays this means:
$a === $b TRUE if $a and $b have the same key/value pairs in the same order and of the same types.
Output (Demo):
Array
(
[0] => Array
(
[a] => 1
[b] => Hello
)
[1] => Array
(
[a] => 1
[b] => other
)
)

First things first, you can not use plain array_unique for this problem because array_unique internally treats the array items as strings, which is why "Cannot convert Array to String" notices will appear when using array_unique for this.
So try this:
$result = array(
0=>array('a'=>1,'b'=>'Hello'),
1=>array('a'=>1,'b'=>'other'),
2=>array('a'=>1,'b'=>'other')
);
$unique = array_map("unserialize", array_unique(array_map("serialize", $result)));
print_r($unique);
Result:
Array
(
[0] => Array
(
[a] => 1
[b] => Hello
)
[1] => Array
(
[a] => 1
[b] => other
)
)
Serialization is very handy for such problems.
If you feel that's too much magic for you, check out this blog post
function array_multi_unique($multiArray){
$uniqueArray = array();
foreach($multiArray as $subArray){
if(!in_array($subArray, $uniqueArray)){
$uniqueArray[] = $subArray;
}
}
return $uniqueArray;
}
$unique = array_multi_unique($result);
print_r($unique);
Ironically, in_array is working for arrays, where array_unique does not.

Related

delete all the duplicate element with array_unique PHP

I have this following array :
Array
(
[1] => Array
(
[0] => 2013-07
[1] => 4
[2] => 4
[3] => 3060
[4] => 1
)
[2] => Array
(
[0] => 2013-07
[1] => 270
[2] => 757
[3] => 13812810
[4] => 4
)
And i want to delete all the duplicated elements and replace $month[1][4] with it sum:
$result = array_reduce($month, function($cur, $x)
{
return $cur + $x[4];
}, 0);
$month = array_unique($month); //<---- Exception
$month[1][4]=$result;
It works fine but it displays me this exception Notice: Array to string conversion !
How can I prevent this from happening?
Thanks
Quick Answer: use:
$unique = array_unique($a, SORT_REGULAR);
// OR
$unique = array_map('unserialize', array_unique(array_map('serialize', $a)));
Explanation
The problem comes about because you're using a multi-dimensional array, array_unique() uses using string conversion before comparing the values to find the unique values:
Note: Two elements are considered equal if and only if (string) $elem1 === (string) $elem2. In words: when the string representation is the same. The first element will be used.
An array will always convert to "Array" when casting it to a string:
var_dump("Array" === (string) array());
You can solve this by specifying the SORT_REGULAR mode in the second parameter of array_unique:
$unique = array_unique($a, SORT_REGULAR);
Or, if that doesn’t work, by serializing the arrays before and unserializing it after calling array_unique to find the unique values:
$unique = array_map('unserialize', array_unique(array_map('serialize', $a)));
This is what you need:
$month= array_unique($month, SORT_REGULAR);

php array_merge_recursive preserving numeric keys

I would simply like to merge
$a = array("59745506"=>array("up" => 0,));
$b = array("59745506"=>array("text" => "jfrj"));
$c = array_merge_recursive_new($a, $b);
result:
Array
(
[0] => Array
(
[up] => 0
)
[1] => Array
(
[text] => jfrj
)
)
expected result:
Array
(
[59745506] => Array
(
[up] => 0
[text] => jfrj
)
)
the 2nd comment in http://www.php.net/manual/en/function.array-merge-recursive.php is working, is it the best solution for my case (where I need to merge arrays with multiple numeric keys, and with 2 levels)?
another workaround would be to implement it with array_map(function ()...
The array_replace_recursive() function looks to be what you need.
$a = array("59745506" => array("up" => 0,));
$b = array("59745506" => array("text" => "jfrj"));
$c = array_replace_recursive($a, $b);
var_export($c);
// array (
// 59745506 =>
// array (
// 'up' => 0,
// 'text' => 'jfrj',
// ),
// )
Your expectation fails as the key of the $a and $b is numeric(!), even though you denoted it as a string literal (cf. PHP: Arrays -> Syntax).
I think whether or not there is a better solution depends on what you exactly need. It might be simpler than merging recursively:
1) Are you sure that every value inside the $a and $b arrays will always be an array again?
2) What is supposed to happen if these arrays share a common key (i.e. if "text" was again "up" in your example)? Keep merging recursively or not?

Array_unshift like function that returns the array

is there a built in function in php that prepends an element to an array, and returns the new array?
instead of returning the new length of the array?
You could use
array_merge()
For example
$resultingArray = array_merge(array($newElement), $originalArray);
Next to array_merge, if there ain't any duplicate keys, you can do:
$array = array('a' => 'A');
$append = array('b' => 'hello');
$array = $append + $array;
Gives:
Array
(
[b] => hello
[a] => A
)
The plus is the array union operator­Docs.
There's no built-in which does it, but it's simple enough to wrap it:
function my_unshift($array, $var) {
array_unshift($array, $var);
return $array;
}
This isn't necessary though, because array_unshift() operates on an array reference so the original is modified in place. array_push(), array_pop(), array_shift() all also operate on a a reference.
$arr = array(1,2,3);
array_unshift($arr, 0);
// No need for return. $arr has been modified
print_arr($arr);
Array
(
[0] => 0
[1] => 1
[2] => 2
[3] => 3
)

php assoc array

I have two assoc array i want to creat one array out of that
E.g
a(a=>1
b=>3
f=>5
)
b(a=>4
e=>7
f=>9
)
output must be
c(
a=>1
b=>3
f=>5
a=>4
e=>7
f=>9
)
i am new in php
Use array_merge(). Your resulting array CAN NOT have more than one entry for the same key, so the second a => something will overwrite the first.
Use the + operator to return the union of two arrays.
The new array is constructed from the left argument first, so $a + $b takes the elements of $a and then merges the elements of $b with them without overwriting duplicated keys. If the keys are numeric, then the second array is just appended.
This ey difference of the + operator and the function, array_merge is that array merge overwrites duplicated keys if the latter arguments contain that key. The documentation puts it better:
If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.
If the keys are different, then use array_merge()
<?php
$a1=array("a"=>"Horse","b"=>"Cat");
$a2=array("c"=>"Cow");
print_r(array_merge($a1,$a2));
?>
OUTPUT:
Array ( [a] => Horse [b] => Cat [c] => Cow )
If the keys are the same, then use array_merge_recursive()
<?php
$ar1 = array("color" => array("favorite" => "red"), 5);
$ar2 = array(10, "color" => array("favorite" => "green", "blue"));
$result = array_merge_recursive($ar1, $ar2);
print_r($result);
?>
OUTPUT:
Array
(
[color] => Array
(
[favorite] => Array
(
[0] => red
[1] => green
)
[0] => blue
)
[0] => 5
[1] => 10
)

The PHP function array_unique doesn't work

I have an array in PHP and I want to remove duplicates.
I simply turned to the function array_unique() to create a new array and remove the duplicates.
Here's the code:
$unlink = array();
$unlink = array_unique($linkphoto);
foreach ($unlink as $link) {
echo $link, "<br />";
}
Still it shows duplicates! Any suggestions about what's wrong?
According to the documentation, the condition for equality is as follows:
Note: Two elements are considered equal if and only if (string) $elem1 === (string) $elem2. In words: when the string representation is the same. The first element will be used.
What sort of data are you using? If two items aren't string equal, then they'll both remain in the array.
We need more context in order to be able to help you, like what the contents are of $linkphoto before array_unique is applied to it. For example:
<?php
$array = Array('A','B','C','D','B');
print_r($array); // Array ( [0] => A [1] => B [2] => C [3] => D [4] => B )
$result = array_unique($array);
print_r($result); // Array ( [0] => A [1] => B [2] => C [3] => D )
?>
As #nobody_ mentioned, it will only eliminate duplicates if their string representations are the same.

Categories