h2O
h2O

Reputation: 544

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.

Upvotes: 1

Views: 7585

Answers (5)

Connor Leech
Connor Leech

Reputation: 18833

The other solutions don't take into account if a name has more than two words. This will save first word as first name and the rest of the words as the last name:

$inputName = "fname lname";
$nameArr   = explode(' ', trim($inputName));
$firstName = $nameArr[0] ?? null;
$lastName  = ($nameArr[1] ?? null) ? implode(' ', array_slice($nameArr, 1)) : null;

Upvotes: 0

AlGhazali
AlGhazali

Reputation: 1

function Split_Name($name) {
//Pass the Full Name to the function

//Trim the Full Name for any paddings
$name = trim($name);

//Split the Full Name by Spaces
$split_name = explode(' ',$name);

//Then iterate through each Name to get the length  
foreach($split_name as $v) {
   $string []= strlen($v);
}

//Get First Name
$first_name = $split_name[0];
//Get Last Name
$last_name = $split_name[count($string)-1];

//Return the Array of Name Example (1)
//return print_r(array($first_name, $last_name));

//Return As Associative Array Example (2)
return print_r(array('FirstName' => $first_name, 'LastName' => $last_name));}

Split_Name('John Adam McMaster');//Example (1) Output Array ( [0] => John [1] => McMaster )

Split_Name('John Adam McMaster');//Example (2) Output Array ( [FirstName] => John [LastName] => McMaster )

Upvotes: -1

Ricardo Canelas
Ricardo Canelas

Reputation: 2460

Example:

<?php
    $fullname = 'Carlos Fernandes Paddington da Costa Silva';
    $fullname = trim($fullname); // remove double space
    $firstname = substr($fullname, 0, strpos($fullname, ' '));
    $lastname = substr($fullname, strpos($fullname, ' '), strlen($fullname));
?>

Upvotes: 3

Tim
Tim

Reputation: 8606

Some other answers here will result in undefined errors under some circumstances. I'd do:

$names = explode(' ', $fullname, 2 );
$fname = array_shift( $names );
$lname = array_shift( $names ) or $lname = '';

Upvotes: -1

Adrian
Adrian

Reputation: 1046

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.

Upvotes: 7

Related Questions