0

How can I get the create the variables with the values out of this string, similar to how you would with $_GET

search=test&site=1&salesperson=2&referral=6&product=10&estimate=1000&sort=date&open=on&filter_sbmt=Filter+Prospect&limit=30

e.g.

$search = 'test';
$site = 1;
etc...
Synapsido
  • 140
  • 3
  • 12
Source
  • 1,026
  • 4
  • 11
  • 23
  • I do not understand what you want. Please reformulate. –  Dec 11 '19 at 01:13
  • yes, that looks like what I want, but how do you set the variables after parse? – Source Dec 11 '19 at 01:19
  • u just do it manually? parse_str($str, $val_arr); $search = $val_arr['search']; or could you do it with a script? – Source Dec 11 '19 at 01:21
  • 3
    Simply dumping the variables into the current scope is usually a _very bad idea_. Is there a particular reason that you can't just use the array? – Sammitch Dec 11 '19 at 01:23
  • So would this be ideal? `foreach($val_arr as $l=>$v) { ${$l} = $v; }' – Source Dec 11 '19 at 01:25
  • 1
    $str = "first=value&arr[]=foo+bar&arr[]=baz"; // Recommended parse_str($str, $output); echo $output['first']; // value echo $output['arr'][0]; // foo bar echo $output['arr'][1]; // baz you also can use for each on this array to get key and value – Jehad Ahmad Jaghoub Dec 11 '19 at 01:34
  • dear @Source , why have you downgraded my solution because it is exactly what you asked for, you wanted the variables in the same way you would get them with $_GET. GET gives you a array, my solution gives you also a array and you can access each variable with $arr['search'] , the way you would access with $_GET['search'] –  Dec 13 '19 at 11:15

1 Answers1

0

Use parse_str() function (https://www.geeksforgeeks.org/php-parse_str-function/)

$str = 'search=test&site=1&salesperson=2&referral=6&product=10&estimate=1000&sort=date&open=on&filter_sbmt=Filter+Prospect&limit=30';
parse_str($str);
echo $search; // 'test'
echo $site; // '1'

Don't try to make this call without storing the result on an array, this is discouraged and deprecated as of PHP 7.2 (https://www.php.net/manual/en/function.parse-str.php)

You have then to pass a result object to store the results on as a second parameter:

$str = 'search=test&site=1&salesperson=2&referral=6&product=10&estimate=1000&sort=date&open=on&filter_sbmt=Filter+Prospect&limit=30';
$output = array();
parse_str($str, $output);
print_r($output); // Array ( [search] => test [site] => 1 ...)
echo $output['search']; // 'test'
echo $output['site']; // '1'
nnimis
  • 464
  • 9
  • 17