php array_unique sorting behavior - php

I am checking the array_unique function. The manual says that it will also sort the values. But I cannot see that it is sorting the values. Please see my sample code.
$input = array("a" => "green", 3=>"red", "b" => "green", 1=>"blue", "red");
print_r($input);
$result = array_unique($input,SORT_STRING);
print_r($result);
The output is
Array
(
[a] => green
[3] => red
[b] => green
[1] => blue
[4] => red
)
Array
(
[a] => green
[3] => red
[1] => blue
)
Here the array $result is not sorted. Any help is appreciated.
Thank you
Pramod

array_unique:
Takes an input array and returns a new array without duplicate values.
Note that keys are preserved. array_unique() keeps the first key encountered for every value, and ignore all following keys.
you can try this to get the result:
<?php
$input = array("a" => "green", 3=>"red", "b" => "green", 1=>"blue", "red");
print_r($input);
$result = array_unique($input);
print_r($result);
asort($result);
print_r($result);

The manual does not say it will sort the array elements, it says that the sort_flags parameters modifies the sorting behavior.
The optional second parameter sort_flags may be used to modify the
sorting behavior using these values: [...]
The sorting behavior is used to sort the array values in order to perform the comparison and determine whether one element is considered to be equal to another. It does not modify the order of the underlying array.
If you want to sort your array, you'll have to do that as a separate operation. Documentation on array sorting can be found here.
For a default ascending sort based on the array's values, you could use asort.

array_unique takes an input array and returns a new array without duplicate values. It doesn't sort actually. Read more at http://php.net/manual/en/function.array-unique.php

Related

sorting array based on child array[0] (unix) value

I need an array sorted by Unix timestamp values. I attempted to use both ksort and krsort before realising that occasionally the timestamp values might be the same (and you cannot have duplicate keys in arrays).
Here's an example array I may be faced with:
$array = array(
[
"unix" => 1556547761, // notice the two duplicate unix values
"random" => 4
],
[
"unix" => 1556547761,
"random" => 2
],
[
"unix" => 1556547769,
"random" => 5
],
[
"unix" => 1556547765, // this should be in the 3rd position
"random" => 9
]
);
So what I'm trying to do is sort them all based on each child arrays unix value, however I cannot figure out how to do so. I have tried countless insane ways (including all other sort functions and many, many for loops) to figure it out - but to no avail.
All help is appreciated.
You can use usort which sort your array by given function
Define function as:
function cmpByUnix($a, $b) {
return $a["unix"] - $b["unix"];
}
And use with: usort($array, "cmpByUnix");
Live example: 3v4l
Notice you can also use asort($array); but this will compare also the "random" field and keep the key - if this what you need then look at Mangesh answer
array_multisort() — Sort multiple or multi-dimensional arrays
array_columns() — Return the values from a single column in the input array
You can use array_multisort() and array_column(), then provide your desired sort order (SORT_ASC or SORT_DESC).
array_multisort(array_column($array, "unix"), SORT_ASC, $array);
Explanation:
In array_multisort(), arrays are sorted by the first array given. You can see we are using array_column($array, "unix"), which means that the second parameter is the order of sorting (ascending or descending) and the third parameter is the original array.
This is the result of array_column($array, "unix"):
Array(
[0] => 1556547761
[1] => 1556547761
[2] => 1556547765
[3] => 1556547769
)
This function sorts an array such that array indices maintain their correlation with the array elements they are associated with. This is used mainly when sorting associative arrays where the actual element order is significant.
Note:If two members compare as equal, their relative order in the sorted array is undefined.
Refer : https://www.php.net/manual/en/function.asort.php
asort($array);
echo "<pre>";
print_r($array);
echo "</pre>";
It will give you the output as
Array
(
[1] => Array
(
[unix] => 1556547761
[random] => 2
)
[0] => Array
(
[unix] => 1556547761
[random] => 4
)
[3] => Array
(
[unix] => 1556547765
[random] => 9
)
[2] => Array
(
[unix] => 1556547769
[random] => 5
)
)
You can keep the array key [1],[0],[3],[2]) as it is Or you can keep it as sequential as per your requirement.

PHP - Why doesn't array_multisort function sort correctly?

please view the following code with 2 arrays. i use multisort function with sort flags for ascending and numeric then display. as you can see in the output that array 2 starts with 100 when it should be last. please explain what is causing this and how to sort it correctly. thank you.
<?php
$array1 = array(1,7,10,6);
$array2 = array(100,20,25,10);
array_multisort($array1, SORT_ASC, SORT_NUMERIC, $array2);
print_r($array1);
echo "<br>";
print_r($array2);
?>
output:
Array ( [0] => 1 [1] => 6 [2] => 7 [3] => 10 )
Array ( [0] => 100 [1] => 10 [2] => 20 [3] => 25 )
Ah, yes, array_multisort is a bit tricky to understand the first time round.
Basically the sort is lexicographical, a fancy word meaning that the first array is sorted and the second arrays elements are ordered according to the first array.
Look at your first (output) array and see the order and map it to the initial second array and you'll see whats happening.
So the second array you take the 1st, 4th , 2nd and 3rd elements.
If you just want plain sorting for multiple arrays then just do them one by one or over a loop.

Check if Array has identical Entries

I got an array, with alot of entries, like:
$array = ['abc', 'def', 'ghi', 'abc'];
Now I wanna check, if there are identical entries in this array.
For example there is 'abc' twice in this array.
When I found identical entries, I wanna filter them out.
Whats the best way to do that without MySQL?
I could just check
if($array[0] == $array[1])
etc
but that would be horrible amount of work, and some bad programming i guess.
Greetings
You can just use array_unqique: http://www.php.net/manual/en/function.array-unique.php
Takes an input array and returns a new array without duplicate values.
Note that keys are preserved. array_unique() sorts the values treated as string at first, then will keep the first key encountered for every value, and ignore all following keys. It does not mean that the key of the first related value from the unsorted array will be kept.
<?php
$input = array("a" => "green", "red", "b" => "green", "blue", "red");
$result = array_unique($input);
print_r($result);
?>
The above example will output:
Array
(
[a] => green
[0] => red
[1] => blue
)

Should I use asort after array_unique if the array was asorted before?

$arr = asort($arr);
//some magic code goes here, $arr is not changed
$arr = array_unique($arr);
Should I use asort again to be sure $arr is asorted?
My tests show that no, I don't. But I'm not sure for 100% if array_unique actually removes the 2nd+ repeated elements.
You merely want to ensure that asort and array_unique use the same sort_flags.
By default:
array array_unique ( array $array [, int $sort_flags = SORT_STRING ] )
bool asort ( array &$array [, int $sort_flags = SORT_REGULAR ] )
So you can see that each will sort based on a different algorithm, which might mostly match up, but you want it to explicitly match up. Thus, the smart money is on making a decision like:
<?php
$input = array("a" => "green", "red", "b" => "green", "blue", "red");
asort($input,SORT_REGULAR);
print_r($input);
print "\n";
$result = array_unique($input,SORT_REGULAR);
print_r($result);
Resulting in:
Array
(
[1] => blue
[a] => green
[b] => green
[2] => red
[0] => red
)
Array
(
[1] => blue
[a] => green
[2] => red
)
Also note that if you merely run array_unique without the initial asort, you will get different results.
Finally note that asort supports two flags that array_unique does not support:
SORT_NATURAL - compare items as strings using "natural ordering"
like natsort()
SORT_FLAG_CASE - can be combined (bitwise OR) with
SORT_STRING or SORT_NATURAL to sort strings case-insensitively
If you use either of these two in your asort then you would necessarily need to asort again after array_unique.
No you do not need to. array_unique will only remove elements, so the order will always be preserved.
If you do not modify the array after the 'asort()', the array will be ordered.
No, you shouldn't. The function array_unique preserves keys, so there is no need to sort it again.

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
)

Categories