1

As a beginner in php, I'm in the situation where I have to reverse the followings strings:

  1. "secondname firstname" as "firstname secondame",
  2. "secondname1 secondname2 firstname" as "firstname secondname1 secondname2"

The code works but it looks like a little bit complicated for such a function.

$name = "secondname1 secondname2 firstname";
$split = explode(" ", $name);

$last = count($split);
$firstname = $split[$last -1];
$secondnames = implode(" ",array_slice($split,-$last, $last-1));

echo implode(" ",array($firstname, $secondnames));

Do you have any idea about something simpler ?

2
  • No, but you can wrap that block into a function of your own design so you'll only have to write it once. The problem is too specific for a PHP function, but it's exactly the kind of thing you write your own functions for. Commented Nov 25, 2014 at 9:32
  • It is already relatively compact for what you are doing. If you have to do it in more than one place wrap it in a function. Commented Nov 25, 2014 at 9:36

1 Answer 1

2

You can pop the last element off the end of the array and then unshift it back to the beginning:

function last_word_first($name) {
    $x = explode(' ', $name);
    array_unshift($x, array_pop($x));
    return implode(' ', $x);
}

echo last_word_first("secondname firstname"), "\n";
echo last_word_first("secondname1 secondname2 firstname"), "\n";

Another option is a regular expression:

function last_word_first($name) {
    return preg_replace('~(.+)\s+(\S+)$~', "$2 $1", $name);
}

On a self-promo note, I've got a library that can do it like this:

$x = str($name)->split();
print $x[':-1']->prepend($x[-1])->join(' ');
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.