Search code examples
phparraysassociative-arraystring-parsingdelimited

Parse an array of delimited values into a flat, associative array


I have an array that looks like this:

Array
(
    [0] => Dog:110
    [1] => Cat:111
    [2] => Mouse:101
)

Based on that array, I want to create another array to look like this

Array
(
   [Dog] => 110
   [Cat] => 111
   [Mouse] => 101
)

I know this is easy by creating my own function. But is there any way to do this with built in php function. Basically, I know I need to explode(), but is there any way to use this function in conjuction with one php's array functions or will I need to create my own function?


Solution

  • For fun one-liner:

    parse_str(str_replace(':', '=', implode('&', $array)), $result);
    print_r($result);