Categories
arrays php

Explode a string to associative array without using loops?

I have a string like 1-350,9-390.99,..., and I need to turn it into an associative array like this:

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

Is it possible to do this using only array functions, without a loop?

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.