phparrayssortingcustom-sort

Move all empty values to the back of the array


How can I move the empty values of an array to the last positions and maintain an indexed array?

Sample input:

$givenArray = array( 
    0 => 'green', 
    1 => '', 
    2 => 'red', 
    3 => '', 
    4 => 'blue'
);

Desired result:

$requiredArray = array(
    0 => 'green',
    1 => 'red',
    2 => 'blue',
    3 => '',
    4 => '' 
);

Provided that the non-empty values should not be sorted (stable sort). It should be as it is, i.e. only the empty values should move to the end of an array.

I need exactly what my examples show.


Solution

  • There are much better/more elegant answers in this thread already, but this works too:

    //strip empties and move to end
    foreach ($givenArray as $key => $value)
    { 
        if ($value === "")
        { 
            unset($givenArray[$key]);
            $givenArray[] = $value;
        }
    }
    
    // rebuild array index
    $givenArray = array_values($givenArray);