phparraysassociative-arraystring-parsing

Parse an array of "key [value]" strings into an associative array


I have the following array:

Array
(
    [0] => 102 [30:27]
    [1] => 110 [29:28]
    [2] => 103 [30:27]
)

The output I need is as follows:

Array
(
    [102] => 30:27
    [110] => 29:28
    [103] => 30:27
)

How can I do this?


Solution

  • If the data is consistent then is there any need for expensive regex? Here's the working version.

    $array = array(
        '102 [30:27]',
        '110 [29:28]',
        '103 [30:27]'
    );
    
    $new = array();
    
    array_walk($array, function($element) use (&$new) {
        $parts = explode(" ", $element);
        $new[$parts[0]] = trim($parts[1], ' []');
    });
    
    var_dump($new);