Search code examples
phparraysassociative-arraytext-parsingdelimited

Parse string with two sets of delimiters and inconsistent spacing and create a flat associative array


I need to explode by "," then ":".

$alttitle = "35:title1,36:title2, 59:title5"
$replacetitles = explode(",",$alttitle);
for ($i = 0 ; $i < count($replacetitles) ; $i++) {
   $replacetitle[] = explode(":", $replacetitles[$i]);
}

Which produces...

Array (
  [0] => Array (
    [0] => 35
    [1] => title1
  )
  [1] => Array (
    [0] => 36
    [1] => title2
  )
  [2] => Array (
    [0] => 59
    [1] => title5
  )
)

...but the number 35,36,59 are unique so I want this to become the key for the array.

Array (
  [35] => title1
  [36] => title2
  [59] => title5
)

Solution

  • Simply set it while looping:

    $alttitle = "35:title1,36:title2, 59:title5"
    $tmptitles = explode(",",$alttitle);
    
    $replacetitle = array();
    foreach($tmptitles as $tmptitle) {
       $tmparr = explode(":", trim($tmptitle));
       $replacetitle[intval($tmparr[0])] = trim($tmparr[1]);
    }
    

    With the above, you will create your array a minimum number of iterations.