Explode a string to associative array without using loops?

Something like this should work:

$string = '1-350,9-390.99';

$a = explode(',', $string);

foreach ($a as $result) {
    $b = explode('-', $result);
    $array[$b[0]] = $b[1];
}

PHP 5.5+ two-line solution, using array_chunk and array_column:

$input  = '1-350,9-390.99';

$chunks = array_chunk(preg_split('/(-|,)/', $input), 2);
$result = array_combine(array_column($chunks, 0), array_column($chunks, 1));

print_r($result);

Yields:

Array
(
    [1] => 350
    [9] => 390.99
)

See it online at 3v4l.org.


Here's a way to do it without a for loop, using array_walk:

$array = explode(',', $string);
$new_array = array();
array_walk($array,'walk', $new_array);

function walk($val, $key, &$new_array){
    $nums = explode('-',$val);
    $new_array[$nums[0]] = $nums[1];
}

Example on Ideone.com.

Tags:

Php

Arrays