PHP asort by value ASC, value 0 should go last

I have the following array:

$values = [
  'a' => 0,
  'b' => 1,
  'c' => 0,
  'd' => 3,
  'e' => 2
];

I need to be able to sort it like so:

$values = [
  'b' => 1,
  'e' => 2,
  'd' => 3,
  'a' => 0,
  'c' => 0
];

The fastest solution I managed to come up with is:

$zero = array_filter($values, fn($val) => $val === 0);

$non_zero = array_diff_assoc($values, $zero);
asort($non_zero);

$result = array_merge($non_zero, $zero);

My question is: is there a better way to do this?

Here is a sandbox version

Thank you!

UPDATE

It looks like this one might work too:

asort($values);
uasort($values, function($a, $b){
    return $a === 0 ? 1 : -1;
});

Any better ideas?



Read more here: https://stackoverflow.com/questions/68462622/php-asort-by-value-asc-value-0-should-go-last

Content Attribution

This content was originally published by Cornel Raiu at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: