Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array_unique SORT_REGULAR flag

Tags:

php

$array = array(1, '1a', '1');
var_export(array_unique($array, SORT_REGULAR));
  • The result: array ( 0 => 1, 2 => '1')
  • In the PHP manual: SORT_REGULAR - compare items normally (don't change types).

What is the logic behind this ? Why or how is '1a' excluded ?

like image 661
johnlemon Avatar asked Feb 10 '13 21:02

johnlemon


1 Answers

This happens because array_unique works by first sorting the values as strings, then iterating over the sorted array and for each value excluding from the result all successive values that compare equal to it.

The comparison function for "comparing equal" above is chosen according to the second parameter, which for SORT_REGULAR is the same as an equality check with ==.

This behavior gives rise to a whole lot of gotchas. Since the sort is quicksort, it's unstable. Therefore sorting an array that contains both 1 and '1' gives no guarantee which one will end up being first in the result. This means that array_unique may appear to arbitrarily "prefer" 1 in some cases and '1' in others.

However the madness continues: consider that if the sort produces [1, '1', '1a'] then '1a' will not be included in the result (it compares equal to 1) while if the sort produces ['1', 1, '1a'] then it will be included (it does not compare equal to the string '1')!

like image 100
Jon Avatar answered Oct 15 '22 22:10

Jon