Search code examples
phpeasyphp

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

<?php
$str= "fname lname";
$len=strlen($str);
$s="";
for($i=0;i<=$len;$i++)
{
$sub=substr($str,$i,($i+1));
if($sub!=" ")
{
$s=s+$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.


Solution

  • 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.