1,105,333 Community Members

Split a list into an array?

Member Avatar
MU.vo.doi.vai.coi.MU
Newbie Poster
2 posts since Jan 2013
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
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.

Member Avatar
deceptikon
Eternally Awesome
4,687 posts since Jan 2012
Reputation Points: 1,341 [?]
Q&As Helped to Solve: 686 [?]
Skill Endorsements: 104 [?]
Administrator
Featured
 
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.
    }
}
Member Avatar
diafol
Where are my eyes?
12,970 posts since Oct 2006
Reputation Points: 1,821 [?]
Q&As Helped to Solve: 1,847 [?]
Skill Endorsements: 92 [?]
Moderator
Featured
Sponsor
 
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.

Member Avatar
MU.vo.doi.vai.coi.MU
Newbie Poster
2 posts since Jan 2013
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
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 three months: Start a new discussion instead
Post:
Start New Discussion
Tags Related to this Article