ramsey_lewis
ramsey_lewis

Reputation: 598

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?

Upvotes: 0

Views: 138

Answers (2)

yuk
yuk

Reputation: 933

You can use this if order doesn't matter:

rsort($myTabs);

Upvotes: 0

splash58
splash58

Reputation: 26153

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) ""
}

Upvotes: 2

Related Questions