0

I have come across a unusual scenario where I need to turn a query string into an array.

The query string comes across as:

?sort%5B0%5D%5Bfield%5D=type&sort%5B0%5D%5Bdir%5D=desc

Which decodes as:

sort[0][field]=type&sort[0][dir]=desc

How do I get this into my PHP as a usable array? i.e.

echo $sort[0][field] ; // Outputs "type"

I have tried evil eval() but with no luck.


I need to explain better, what I need is the literal string of sort%5B0%5D%5Bfield%5D=type&sort%5B0%5D%5Bdir%5D=desc to come into my script and stored as a variable, because it will be passed as a parameter in a function.

How do I do that?

1
  • You wouldnt want to run eval on a string you are pulling directly from the query string. That would be a massive security flaw. Commented Jan 10, 2013 at 14:49

2 Answers 2

2

PHP will convert that format to an array for you.

header("content-type: text/plain");
print_r($_GET);

gives:

Array
(
    [sort] => Array
        (
            [0] => Array
                (
                    [field] => type
                    [dir] => desc
                )

        )

)

If you mean that you have that string as a string and not as the query string input into your webpage, then use the parse_str function to convert it.

header("content-type: text/plain");
$string = "sort%5B0%5D%5Bfield%5D=type&sort%5B0%5D%5Bdir%5D=desc";
$array = Array();
parse_str($string, $array);
print_r($array);

… gives the same output.

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

2 Comments

How would i get parse_str() to ignore arrays in the query string?
That's exactly the opposite of what you asked for… use $_SERVER['QUERY_STRING'] if you want to get the raw query string.
0

Use parse_str()

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

<?php
$str = "first=value&arr[]=foo+bar&arr[]=baz";
parse_str($str);
vecho $first;  // value
echo $arr[0]; // foo bar
echo $arr[1]; // baz


parse_str($str, $output);
echo $output['first'];  // value
echo $output['arr'][0]; // foo bar
echo $output['arr'][1]; // baz

?>

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.