h2O h2O - 1 year ago 92
PHP Question

php code to extract firstname and lastname from fullname

I am a very beginner in php. I want to extract the first name and the last name from the full name. The following was my code :-

$str= "fname lname";
if($sub!=" ")
else {break;}
echo $s;

The problem with this code is that the loop runs infinitely and a fatal error is caused.
Any help will be appreciated.

Answer Source

This is a quick and easy way.

$name = 'John Smith';

list($firstName, $lastName) = explode(' ', $name);

echo $firstName;
echo $lastName;

But if you want to take into account middle names etc,

$name = 'John Mark Smith';
$name = explode(' ', $name);

$firstName = $name[0];
$lastName = (isset($name[count($name)-1])) ? $name[count($name)-1] : '';

The second approach would be better, as it will work for 1 name too.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download