phparrayssortingcustom-sortstable-sort

Move null items to the end of an array


I have an array like:

array (size=5)
    0 => "" 
    1 => ""
    2 => "foo"
    3 => ""
    4 => "bar"

I want to move all of the empty items to the end, but keep them:

array (size=5)
    0 => "foo" 
    1 => "bar"
    2 => ""
    3 => ""
    4 => ""

I tried to do array_values(array_filter($myTab)) but result as:

array (size=2)
    0 => "foo" 
    1 => "bar"

How to keep the empty item in php?


Solution

  • You can do it in one line. I did make some to putt comments

    $myTab = array (
    "", 
    "",
    "foo",
    "",
    "bar");
    
    // all not empty values
    $a = array_filter($myTab);
    // all empty values (rest in array)
    $b = array_diff($myTab, $a);
    // Full array
    $new = array_merge($a, $b);
    var_dump($new);
    

    result

    array(5) {
      [0]=>
      string(3) "foo"
      [1]=>
      string(3) "bar"
      [2]=>
      string(0) ""
      [3]=>
      string(0) ""
      [4]=>
      string(0) ""
    }