Shane McCarthy
Shane McCarthy

Reputation: 109

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?

Upvotes: 0

Views: 129

Answers (4)

mickmackusa
mickmackusa

Reputation: 48031

More approaches:

preg_match_all() with array_combine() to build the associative array. Demo

$str = 'value,0.23,word,0.42,dog,0.28000000000000014,cat,0,car,17.369999999999997';

preg_match_all('#([^,]+),([^,]+)#', $str, $m);
var_export(array_combine($m[1], $m[2]));

Or explode, chunk, transpose, then combine. Demo

var_export(
    array_combine(
        ...array_map(
            null,
            ...array_chunk(
                explode(',', $str),
                2
            )
        )
    )
);

Or a body-less loop with array destructuring syntax. Demo

$result = [];
foreach (
    array_chunk(explode(',', $str), 2)
    as
    [$k, $result[$k]]
);
var_export($result);

Upvotes: 0

Ja͢ck
Ja͢ck

Reputation: 173652

You can use array_chunk():

$values = array_chunk(explode(',', $string), 2)

foreach ($values as $pair) {
    list($key, $value) = $pair;
    // do something
}

Upvotes: 1

hek2mgl
hek2mgl

Reputation: 158170

You can use the following code:

$str = 'value,0.23,word,0.42,dog,0.28000000000000014,cat,0,car,17.369999999999997';
$parts = explode(',', $str);
$result = array();
for($i=0; $i < count($parts); $i+=2) {
    $result[$parts[$i]] = $parts[$i+1];
}

var_dump($result);

Output:

array(5) {
  ["value"]=>
  string(4) "0.23"
  ["word"]=>
  string(4) "0.42"
  ["dog"]=>
  string(19) "0.28000000000000014"
  ["cat"]=>
  string(1) "0"
  ["car"]=>
  string(18) "17.369999999999997"
}

Upvotes: 0

Avinash Raj
Avinash Raj

Reputation: 174816

You could try the below regex to get the key, value pairs.

([a-z]+),(\d+(?:\.\d+)?)

DEMO

Upvotes: 2

Related Questions