I'm trying to explode user's name which is a full name string. I'm trying the following:
function name_letters_explode($name) {
$letters = explode(' ', $name);
if(count($letters) > 1) {
return substr($letters[0], 0, 1) . substr($letters[1], 0, 1);
} else {
return substr($name, 0, 1);
}
}
name_letters_explode($user->name);
but there is nothing in return. When I remove the if count condition (that is to check if user inputted 1 name or its full (2 parts) name so I can decide what to return - I'm getting an error undefined array key 1 (the name contain 2 parts and I'm absolutely sure, so it can't be that there is no second name in the string). What to do?
CodePudding user response:
I'm absolutely sure, so it can't be that there is no second name in the string
PHP absolutely sure there is no $letters[1]
;)
If I understood the task correctly, need to get initials
$getInitials = function (string $fullName): string
{
$initials = '';
$parts = explode(' ', $fullName, 2);
foreach ($parts as $part) {
$initials .= mb_substr($part, 0, 1);
}
return $initials;
};
// test
$fullNames = [
'John Doe',
'Иван Иванов',
];
foreach ($fullNames as $fullName) {
$initials = $getInitials($fullName);
var_dump($initials);
}
Pay attention, this is suitable for avatar generation, but not for business correspondence: a double names Anna-Maria Garcia, right-to-left names, etc.
CodePudding user response:
First you need the count condation.because mady the name is null or have not space(' ').
Likely you define your function inside another function or a class method. It can be done, but since functions are defined in the global scope this will result in an error if the method is called twice since the PHP engine will consider the function to be redefined during the second call.
Second if your code is inside a class method, you dont need to make a function and you can past your code outside a function
public function index(){
$name = "milad pegah";
$letters = explode(' ', $name);
if(count($letters) > 1) {
return substr($letters[0], 0, 1) . substr($letters[1], 0, 1);
} else {
return substr($name, 0, 1);
}
}
or you can write your code in another method and return that in your target method.
public function name_letters_explode($name) {
$letters = explode(' ', $name);
if(count($letters) > 1) {
return substr($letters[0], 0, 1) . substr($letters[1], 0, 1);
} else {
return substr($name, 0, 1);
}
}
public function index(){
$name = "milad pegah";
return $this->name_letters_explode($name);
}
else(outside of a class your code is ok and it will work.