0

Consider I have a string in PHP like this:

$a = "a=hello&b=welcome&c=getlost&d=sitHere";

I want to make an array like this:

$b = ["a" => "hello", "b" => "welcome", …];

Is it possible? I think it is possible using explode.

I get this data from an AJAX request.

2 Answers 2

3

Try this :

$a="a=hello&b=welcome&c=getlost&d=sitHere";

parse_str($a, $b);

print_r($b);

See manual: http://www.php.net/manual/en/function.parse-str.php

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

2 Comments

parse_str always trips me up in that it doesn't return anything, but will put it into the second parameter you send it.
@OscarM. that (and its confusing name) is why you should wrap it. :)
1

Wrap the horribly named function parse_str in a nicer API:

function parse_query_string($query_string) {
    $result = [];
    parse_str($query_string, $result);
    return $result;
}

Then just pass it the string and it returns the associative array.

1 Comment

Yep The function name is horrible but it is very usable..Thanks.

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.