phparrayssortingcustom-sort

Move empty values to the end of the array without maintaining relationships to keys


I'm trying to create a function that shifts array values up a key if the previous key is empty and one after is set. E.g. this array:

array (size=4)
    'row1' => string 'row1' (length=4)
    'row2' => string '' (length=0)
    'row3' => string '' (length=0)
    'row4' => string 'row4' (length=4)

should become this after my function call:

array (size=4)
    'row1' => string 'row1' (length=4)
    'row2' => string 'row4' (length=4)
    'row3' => string '' (length=0)
    'row4' => string '' (length=0)

I do have a working function, however, it uses a lot of if statements and I'm 100% sure that it could be done more efficiently, any ideas on how to achieve efficiently?


Solution

  • Lets try this with a big array, and hope this will help you out. The way of question is different but your question is same as

    1. Getting empty values at end.

    2. Non empty at starting without changing order

    3. Without changing keys order

    If you think about any array this result come to end.

    Try this code snippet here

    <?php
    
    $array=$tempArray=array(
        'row1' =>  'row1',
        'row2' =>  '' ,
        'row3' =>  '',
        'row6' =>  'row6' ,
        'row4' =>  'row4' ,
        'row5' =>  '',
        'row7' =>  'row7' ,
        'row8' =>  ''
    );
    $result=array();
    $tempArray=  array_values($tempArray);
    $tempArray=array_values(array_filter($tempArray));
    
    foreach(array_keys($array) as $key_key => $key)
    {
        if(!empty($tempArray[$key_key]))
        {
            $result[$key]=$tempArray[$key_key];   
        }
        else
        {
            $result[$key]="";
        }
    }
    print_r($result);
    

    Output:

    Array
    (
        [row1] => row1
        [row2] => row6
        [row3] => row4
        [row6] => row7
        [row4] => 
        [row5] => 
        [row7] => 
        [row8] => 
    )