phparraysexplode

Convert every two values of a comma-separated string into key-value pairs


I have a string:

$content = "test,something,other,things,data,example";

I want to create an array where the first item is the key and the second one the value.

It should look like this:

Array
(
    [test] => something
    [other] => things
    [data] => example
)

How can I do that? It's difficult to search for a solution because I don't know how to search this.

It's very similar to this: Explode string into array with key and value

But I don't have a json array.

I tried something like that:

$content = "test,something,other,things,data,example";

$arr = explode(',', $content);

$counter = 1;
$result = array();

foreach($arr as $item) {
    if($counter % 2 == 0) {
        $result[$temp] = $item;
        unset($temp);
        $counter++;
    } else {
        $temp = $item;
        $counter++;
        continue;
    }
}

print_r($result);

But it's a dirty solution. Is there any better way?


Solution

  • Try this:

    $array = explode(',',$content);
    $size = count($array);
    for($i=0; $i<$size; $i++)
        $result[$array[$i]] = $array[++$i];