0

I have a set of query strings stored in a database as so

&foo=bar&foo2=bar2

How would I successfully iterate through this string to extract each key and value into an array using the keys as the array keys too?

Had a look around and other questions on here seem to only be for one value.

Danny
  • 579
  • 2
  • 7
  • 13

2 Answers2

1

You can try to use parse_str

<?php
$string = "&foo=bar&foo2=bar2";
parse_str($string, $output);
print_r($output);

See it here https://eval.in/484197

0
function string2KeyedArray($string, $delimiter = '&', $kv = '=') {
  if ($a = explode($delimiter, $string)) { // create parts
foreach ($a as $s) { // each part
  if ($s) {
    if ($pos = strpos($s, $kv)) { // key/value delimiter
      $ka[trim(substr($s, 0, $pos))] = trim(substr($s, $pos + strlen($kv)));
    } else { // key delimiter not found
      $ka[] = trim($s);
    }
  }
}
return $ka;
  }
} 

Now you can use

$string = "&foo=bar&foo2=bar2";
print_r(string2KeyedArray($string));

//Output: Array ( [foo] => bar [foo2] => bar2 )
Huzaib Shafi
  • 1,153
  • 9
  • 24