Search code examples
phparrayssortingksort

how can i sort array which is create of a loop?


function sortpm($parameters){
if(strpos($parameters,"&")!==false){
    foreach(explode("&",$parameters) as $pmsplit){
        $key = explode("=",$pmsplit)[0];
        $value = explode("=",$pmsplit)[1];
        $fields[]=[$key=>$value];
    }
   $parameters = ksort($fields);
}else{
        $parameters = $parameters;
}
print_r($parameters);
}

when i get sortpm("z=4&a=2"); array are not sorted by keys

i want this output: Array ( [a] => 2[z] => 4 )


Solution

  • ksort will sort the $fields array and will return a boolean. You would want something like this:

    $parameters = $fields;
    ksort($parameters);
    

    There are also some unnecessary things happening here. I would rewrite your code like this:

    function sortpm($parameters){
        // Make sure to set a default value to your variables
        $fields = [];
        // No need for the if case - explode will always return an array
        foreach(explode("&",$parameters) as $pmsplit){
            // Instead of exploding twice - explode once, but set a limit
            $exploded = explode("=", $pmsplit, 2);
            // If there is no second parameter, fill in a null value
            $fields[$exploded[0]]= isset($exploded[1]) ? $exploded[1] : null;
        }
       ksort($fields);
       print_r($fields);
    }
    

    Alternatively you could use parse_str as AymDev pointed out.