0

I have a string "key1=value1,key2=value2,...,key-n=value-n".

Without knowing what n is, how can I parse the string to an associative array like:

$result = ["key1" => "value1", "key2" => "value2",...,"key-n" => "value-n"];
zx8754
  • 52,746
  • 12
  • 114
  • 209
namln-hust
  • 309
  • 3
  • 9

2 Answers2

1

In your example it seems like you just want to extract and separate keys and values.

$result = [];
foreach (explode(',', $string) as $pair) {
  list($key, $value) = explode('=', $pair);
  $result[$key] = $value;
}

If you need to throw some regex magic to make sure it conforms to a certain syntax. Here is an example:

$result = [];
foreach (explode(',', $string) as $pair) {
  if (!preg_match('#^(.+-?.*)=(.+-?.*)$#', $pair, $matches)) continue;
  $result[$matches[1]] = $matches[2];
}
tim
  • 2,530
  • 3
  • 26
  • 45
0

You could parse the string as a CSV then explode on the = signs.

$array = str_getcsv('key1=value1,key2=value2,...,key-n=value-n');
$newarray = array();
foreach($array as $pairs){
    if(strpos($pairs, '=') !== FALSE){
        list($key, $value) = explode('=', $pairs);
        $newarray[$key] = $value;
    } else {
        //no value present, what to do?
    }
}
print_r($newarray);

https://3v4l.org/hkYil

user3783243
  • 5,368
  • 5
  • 22
  • 41
  • Can u tell me the difference between explode and str_getcsv? – namln-hust Jun 08 '22 at 03:47
  • 1
    `str_getcsv` is for parsing a CSV, https://www.php.net/manual/en/function.str-getcsv.php, can also be used for other strings with delimiters. You can define the delimiter, enclosure character, as well as an escape character for the data. Explode can't do those things. – user3783243 Jun 08 '22 at 11:32
  • Many thanks, however I just need a simpler solution, so I'll go with tim's answer. – namln-hust Jun 10 '22 at 07:32