Search code examples
phparraysassociative-arraytext-parsingdelimited

Parse string with two sets of delimiters to form an associative array


Input:

$this->request->get(['opt']) = '337:230,323:112';

My Current Code:

$option = explode(",", $this->request->get['opt']);

foreach ($option as $key => $value) {
    echo $value . "<br>";       
}

My Results:

337:230
323:112

Question: How can I separate the above data into an associative array?

Desired Result:

[
    337 => 230, 
    323 => 112,
]

Solution

  • It looks like you just need to explode again on the colons, so perhaps something like this?

    <?php
    
    $opt = '337:230,323:112';
    
    $option = explode(",", $opt);
    
    foreach ($option as $pair) {
        list(key, $value) = explode(':', $pair);
        $array[$key] = $value;
    }
    
    print_r($array);
    
    Array
    (
        [337] => 230
        [323] => 112
    )