phparrayssortingcustom-sort

Move empty value to the end of the array


I have an array something like below.

Array
(
    [0] => 100
    [1] => 
    [2] => 107
    [3] => 109
)

I may get empty value more than one also. I just wanted to move the empty values to down.


Solution

  • I'd just sort it in reverse order

    arsort($myarray, SORT_NUMERIC);
    

    You'd end up with the values:

    109, 107, 100, <blank>
    

    Edit: to get the values in the order specified in the below comment:

    // initial data
    $a = (100, '', 107, 109);
    
    // define functions to detect blank/notblank
    function isBlank($var) {
        return $var == '';
    }
    
    function isNotBlank($var) {
        return !isBlank($var);
    }
    
    // get two arrays, one containing blanks, one containing numbers
    $blanks = array_filter($a, 'isBlank');
    $notBlanks = array_filter($a, 'isNotBlank');
    
    // reverse sort the numbers
    arsort($notBlanks, SORT_NUMERIC);
    
    // merge the arrays
    $output = array_merge($notBlanks, $blanks);
    

    array_merge documentation