Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP implode explode first and last array value

i'm still a freshman on PHP. So i have a variable called 'full name' and i was trying to explode and implode the first and the last variable value.

$fullname='Andre Filipe da Costa Ferreira';
$namepieces=explode('', $fullname);
$flname=implode('', namepieces[0], namepieces[lastvar]);
echo "Welcome".$flname;

I would appreciate if someone could help me! Thanks :D

like image 808
André Ferreira Avatar asked May 10 '26 04:05

André Ferreira


2 Answers

This with name pieces separated with a space, and works with a single name piece like Andre:

<?php
$fullname = 'Andre Filipe da Costa Ferreira';
$namepieces = explode(' ', $fullname);
$n = count($namepieces);
if($n > 1) {
  $flname = implode(' ', array($namepieces[0], $namepieces[$n-1]));
} else {
  $flname = $namepieces[0];
}
echo "Welcome " . $flname;
//
?>

This gets:

Welcome Andre Ferreira
like image 86
jacouh Avatar answered May 11 '26 19:05

jacouh


Try:

$names = explode(" ", "Andre Filipe da Costa Ferreira");
printf("Welcome %s %s", current($names), end($names));

where current() gets its first element, and end() last one.

like image 23
kenorb Avatar answered May 11 '26 19:05

kenorb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!