Home > Enterprise >  Separate string by comma and convert to associative array
Separate string by comma and convert to associative array

Time:06-08

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"];

CodePudding user response:

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

CodePudding user response:

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];
}
  • Related