1.11M Members

Split a list into an array?

 
0
 

I got a list like that
"Name: John, Age: 20, Phone number: 12343223"
How can I make up an array of which indexes are 'name', 'age', .......

Thanks for your help.

 
3
 

You could build the array up manually using nested explodes:

$fields = explode(',', 'Name: John, Age: 20, Phone number: 12343223');
$result = array();

foreach ($fields as $field)
{
    $kvpair = explode(':', $field);

    if (isset($kvpair[0]) && isset($kvpair[1]))
    {
        // Both key and value exist (expected case)
        $result[trim($kvpair[0])] = trim($kvpair[1]);
    }
    else if (isset($kvpair[0]))
    {
        // Only the key exists. May be an error depending
        // on the application, but a sensible default is
        // to accept it with an empty string value.
        $result[trim($kvpair[0])] = '';
    }
    else
    {
        // $field represents an empty field from the source
        // string. A sensible default is to ignore it, but
        // raising an error works too.
    }
}
 
0
 

Maybe this too:

$str = "Name: John, Age: 20, Phone number: 12343223";
$bits = preg_split("/(: )|(, )/",$str);
for($x=0;$x < count($bits)-1;$x += 2)$r[$bits[$x]] = $bits[$x + 1]; 
print_r($r);

Perhaps using trim would be a safe precaution too. Then you could just split on ':' and ',' without the spaces.
Not as safe as D's, as there's no checking for pairs.

 
0
 

You could build the array up manually using nested explodes:

Many thanks for that. It worked like a charm, although I had to put some addition to it to perfectly fit for my work.

For diafol's code, I haven't tried yet, but i suppose it'll work as well. Also thank for your help :)

You
This article has been dead for over six months: Start a new discussion instead
Post:
Start New Discussion
Tags Related to this Article