phparraysassociative-arraystring-parsingdelimited

Convert string with two sets of delimiters into an associative array


I have a variable that contains text with values according to an example below:

$data = "5:7|4:1|504:2|1:3|"

And I would like to achieve results like this:

$data[5] = 7;
$data[4] = 1;
$data[504] = 2;
$data[1] = 3;

I tried with explode:

$data = explode("|", $data);

//but it makes $data[0]="5:7"; $data[1]="4:1"; and so on.

Should I use explode again? Is it has any sense, or is there another way?


Solution

  • There may be a more clever way, but I'd do it like this:

    $data = array();
    foreach (explode("|", $your_data) as $part)
    {
        $pieces = explode(':', $part);
        // Assumes we have 2 pieces, might want to make sure here...
    
        $data[$pieces[0]] = $pieces[1];
    }
    

    Output: demo

    Warning: Undefined array key 1
    array (
      5 => '7',
      4 => '1',
      504 => '2',
      1 => '3',
      '' => NULL,
    )
    

    Also, I'm not sure what this data represents but keep in mind that array keys will overwrite each other, so 1:1|1:2 will result in an array with only one item (the last piece). There may be good reason to take another approach.