I
I
Ilya Pavlov2015-10-18 00:23:54
PHP
Ilya Pavlov, 2015-10-18 00:23:54

Make an array of type (key => value) from a string?

There is a line :
$ne_do_array = "key:val|key2:val2|key3:val3";
We need an array :

$array = [
  'key' => 'val',
  'key2' => 'val2',
  'key3' => 'val3'
];

Of course, you can do all this through cycles, but is there an easier way?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Immortal_pony, 2015-10-18
@PiCoderman

function parse($str) {
    $parsed = [];

    foreach (explode("|", $str) as $elem) {
        list($key, $val) = explode(":", $elem);
        
        $parsed[$key] = $val;
    }

    return $parsed;
}

Yes, if the string is encoded by standard means - for example, json, serialize, http_query.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question