n92
n92

Reputation: 7602

How to get comma separated values from the string in php

I have a string $employee="Mr vinay HS,engineer,Bangalore";. i want to store Mr vinay H S in $name ,engineer in $job and Bangalore in $location. how to do this

Upvotes: 6

Views: 18051

Answers (8)

Spudley
Spudley

Reputation: 168695

list($name,$job,$location) = explode(',',$employee);

Note: this will obviously only work if the string is in the format you specified. If you have any extra commas, or too few, then you'll have problems.

It's also worth pointing out that PHP has dedicated functions for handling CSV formatted data.

See the manual page for str_getcsv for more info.

While explode() is the quickest and easiest way to do it, using str_getcsv() rather than simple explode() will allow you to handle input more complex input, eg containing quoted strings, etc.

Upvotes: 4

Radoslav Georgiev
Radoslav Georgiev

Reputation: 1376

Or you can use another function to do that - http://php.net/manual/en/function.str-getcsv.php

list($name,$job,$location) = str_getcsv($employee);

Upvotes: 3

yogsma
yogsma

Reputation: 10584

$record = explode(",",$employee);
$name = $record[0];
$job = $record[1];
$location = $record[2];

Upvotes: 11

Arjen
Arjen

Reputation: 1321

You can look at the explode() and list() functions:

list($name, $job, $location) = explode(",", $employee);

Upvotes: 2

Rion Williams
Rion Williams

Reputation: 76557

Something like the following should work:

//The employee name
$employee= "Mr vinay HS,engineer,Bangalore";

//Breaks each portion of the employee's name up
list($name, $job, $location) = explode(',',$employee);

//Outputs the employee's credentials
echo "Name: $name; Job: $job; Location: $location";

Upvotes: 3

John Giotta
John Giotta

Reputation: 16944

Use the list function to take the exploded array into 3 variables

list($name, $job, $location) = explode(',', $employee);

Upvotes: 7

mpen
mpen

Reputation: 282895

list($name,$job,$location) = explode(',',$employee);

Upvotes: 3

Peter
Peter

Reputation: 48958

explode will do just that I guess

http://php.net/manual/en/function.explode.php

Any more help on this would suffer from givemethecode-ism, so I leave you to it ;-)

Upvotes: 3

Related Questions