3

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

André Ferreira
  • 185
  • 1
  • 3
  • 16
  • You're missing the `$` in front of `namepieces` on line 3; otherwise - what is the issue that you're having? Do you get an error message? A blank screen? The wrong data? – andrewsi Nov 29 '13 at 18:14
  • yes, please clarify with an example: what _would_ input look like, what _should_ output be – hanzo2001 Nov 29 '13 at 18:19

5 Answers5

2

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
jacouh
  • 8,473
  • 5
  • 32
  • 43
2

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.

kenorb
  • 155,785
  • 88
  • 678
  • 743
1

You need to use end($namepieces); which returns the value of the last element or FALSE for empty array.Also your are missing $ before namepieces

$flname=implode('', $namepieces[0], end($namepieces));

end()

Another example taken from php.net for getting first and last element from array

$items = array( 'one', 'two', 'three' );
$lastItem = end( $items ); // three
$current = current( $items ); // one
M Khalid Junaid
  • 63,861
  • 10
  • 90
  • 118
1
<?php
$fullname = 'Andre Filipe da Costa Ferreira';
$namepieces = explode(' ', $fullname);
$flname = implode(' ', array($namepieces[0], $namepieces[count($namepieces)-1]));
echo "Welcome " . $flname;
//
?>
Mahendra Jella
  • 5,450
  • 1
  • 33
  • 38
0

Its beter way I guess

<?php
$fullname = 'Andre Filipe da Costa Ferreira';
$namepieces = explode(' ', $fullname);
$n = count($namepieces);
$n > 0 ? $flname = implode(' ', array($namepieces[0], $namepieces[$n-1])) : $flname = $namepieces[0];
echo "Welcome " . $flname;
//
?>
Mahendra Jella
  • 5,450
  • 1
  • 33
  • 38