We're a community of 1077K IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,076,466 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion

Split a list into an array?

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
Contributors
3
Replies
21 Hours
Discussion Span
4 Months Ago
Last Updated
5
Views
MU.vo.doi.vai.coi.MU
Newbie Poster
2 posts since Jan 2013
Reputation Points: 0
Solved Threads: 0
Skill Endorsements: 0

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.
    }
}
deceptikon
Challenge Accepted
Administrator
3,460 posts since Jan 2012
Reputation Points: 822
Solved Threads: 474
Skill Endorsements: 57

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.

diafol
Keep Smiling
Moderator
10,675 posts since Oct 2006
Reputation Points: 1,632
Solved Threads: 1,514
Skill Endorsements: 57

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 :)

MU.vo.doi.vai.coi.MU
Newbie Poster
2 posts since Jan 2013
Reputation Points: 0
Solved Threads: 0
Skill Endorsements: 0

This article has been dead for over three months: Start a new discussion instead

Post: Markdown Syntax: Formatting Help
 
You
 
© 2013 DaniWeb® LLC
Page rendered in 0.0665 seconds using 2.75MB