phpstringcsvassociative-arraystring-parsing

Convert every two values in a comma-separated string into associative array elements


I've a string of key value pairs with a comma as a delimiter. I need to go through the string get the key and value and push them into an array.

I'm having an issue with writing a Regex as the value is a decimal number. An example of the string is as follows:

 value,0.23,word,0.42,dog,0.28000000000000014,cat,0,car,17.369999999999997

Any idea how to write a correct regex?


Solution

  • You can use array_chunk():

    $values = array_chunk(explode(',', $string), 2)
    
    foreach ($values as $pair) {
        list($key, $value) = $pair;
        // do something
    }