2

I am trying to use array_map function to parse query string and get a key=>value pair:

function parse_query_string($string)
{
    $result = [];
    $arry = explode('&',$string);

    $get_qry_str_array = function($str, &$result) 
    {
        $a = explode('=',$str);
        $result[$a[0]] = $a[1];
    };

    array_map($get_qry_str_array,$arry, $result);
    return $result;
}

if i use this function as below i was expecting it would return an associative array with each query string parameter and value as key=>value pair because i am passing the $result variable as reference.

$qry_str_array = parse_query_string('edit=1&delete=2');

print_r($qry_str_array);

That is i am expecting an array like:

[
    'edit' => 1,
    'delete' => 2,

] 

but i am getting an empty array.

Am i using this in a wrong way? I am new to php world, relatively.

Yeasir Arafat Majumder
  • 1,222
  • 2
  • 15
  • 34
  • 1
    Just use `http://php.net/manual/en/function.parse-str.php` to parser such strings – splash58 Feb 11 '18 at 10:51
  • I will look into that. But i am actually being curious here. Why is it not working - @splash58? – Yeasir Arafat Majumder Feb 11 '18 at 10:53
  • 1
    array_map set just one argumet for each array so your function does not receive result . do it `$get_qry_str_array = function($str) use(&$result)` – splash58 Feb 11 '18 at 10:55
  • `array array_map ( callable $callback , array $array1 [, array $... ] )` - the function definition says that additional arguments can be passed to be used as the arguments of the callback function. It's from the documentation and there are examples of that too... - @splash58 – Yeasir Arafat Majumder Feb 11 '18 at 11:01
  • Possible duplicate of [How to convert array first value as key and second value as value](https://stackoverflow.com/questions/43559841/how-to-convert-array-first-value-as-key-and-second-value-as-value) – Nicholas Shanks Aug 23 '18 at 09:16
  • See https://stackoverflow.com/questions/43559841/how-to-convert-array-first-value-as-key-and-second-value-as-value for an example of doing this. You don't need to use a reference to build up the outer array. – Nicholas Shanks Aug 23 '18 at 09:17

0 Answers0