phparraysassociative-arraystring-parsingdelimited

Explode a string with two sets of delimiters into an 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?


Solution

  • 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 3v4l.org.

    Output:

    Parse error: syntax error, unexpected token "&", expecting ")"