5

Possible Duplicate:
Parse query string into an array

What's the fastest method, to parse a string of URL parameters into an array of accessible variables?

$current_param = 'name=Peter&car=Volvo&pizza=Diavola&....';

// Results in a nice array that I can pass:

$result = array (
    'name'  => 'Peter',
    'car'   => 'Volvo',
    'pizza' => 'Diavola'
)

I've tested a regular expression, but this takes way too long. My script needs to parse about 10000+ URLs at once sometimes :-(

KISS - keep it simple, stupid

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
mate64
  • 9,876
  • 17
  • 64
  • 96
  • The fastest method is to use `parse_str`. Regular expressions are way too expensive and the algorithm to parse a URL is very simple. That's the fastest way on **one** machine. If you require performance, you can always split the work across many machines but that's both more expensive and tiny bit harder to implement, especially with PHP. – N.B. Dec 27 '11 at 11:14

2 Answers2

38

Use parse_str().

$current_param = "name=Peter&car=Volvo&pizza=Diavola";
parse_str($current_param, $result);
print_r($result);

The above will output

Array
(
    [name] => Peter
    [car] => Volvo
    [pizza] => Diavola
)
kba
  • 19,333
  • 5
  • 62
  • 89
3

The parse_str() function can do the trick as you expect:

<?php
    $str = "first=value&arr[]=foo+bar&arr[]=baz";
    parse_str($str);
    echo $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
?>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Manigandan Arjunan
  • 2,260
  • 1
  • 25
  • 42