Of course I can sort an array sort()
, eliminate duplicates array_unique()
and eliminate blanks array_filter()
. I could do that in three lines, and then repeat those three lines for the ten arrays I have to process.
But I wanted it to be at least slightly elegant, so I tried to combine all three operations. It did work for the first two, then I pushed it too far and applied the sort()
$testArray = sort(array_filter(array_unique($testArray)));
This produced:
Strict Standards: Only variables should be passed by reference
So what would be the most elegant way to accomplish this array processing goal?
Bonus points for helping me understand why it failed.
Just as a prove of concept you can kind of avoid creating in-between variables and mutating the original array. Take a look at SplMinHeap
from Standard PHP Library (SPL). You can use this class for immutable sorting:
$testArray = iterator_to_array(array_reduce(
array_filter(array_unique($testArray)),
function ($heap, $element) {
$heap->insert($element);
return $heap;
},
new SplMinHeap
));
Here is working demo.
Your code $testArray = sort(array_filter(array_unique($testArray)));
doesn't work as you expect due to a misuse of sort()
function:
sort()
returned values are TRUE
or FALSE
. Not an array as you expect.sort()
elements of the recived array parameter will be arranged on the array itself. So it needs an actual array to work on it; not the resturned value of other functions, which doesn't really exists as a variable. That's the reason of the errorOnly variables should be passed by reference in...
Knowing that, and having in mind that in PHP the value of an assignment expression is the value assigned. That is, the value of "$a = 3" is 3 . a first approach to fix the error might be:
sort($testArray = array_filter(array_unique($testArray)));
...but it won't work either. The assignment return the value of $testArray, not $testArray itself. Same problem as before.
At this point, the easiest way of solving so without unnecessary overhead: use two lines of code instead of one.
$testArray = array_filter(array_unique($testArray));
sort($testArray);
Test it here.