Reputation: 7602
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
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
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
Reputation: 10584
$record = explode(",",$employee);
$name = $record[0];
$job = $record[1];
$location = $record[2];
Upvotes: 11
Reputation: 1321
You can look at the explode() and list() functions:
list($name, $job, $location) = explode(",", $employee);
Upvotes: 2
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
Reputation: 16944
Use the list
function to take the exploded array into 3 variables
list($name, $job, $location) = explode(',', $employee);
Upvotes: 7
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