0
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 )

1
  • 1
    What's the actual output ? I get 1 when I run your function with the provided input. Also, you should probably use parse_str(). Commented Aug 6, 2021 at 7:58

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.