Bring the first word to the end

We have an array with the names:

array(
Robin Hood,
Little John,
Maid Marion,
Friar Tuck,
Will Scarlet
)

The first word inside each element should be moved to the end of that element.

We should get the following:

array(
Hood Robin,
John Little,
Marion Maid,
Tuck Friar,
Scarlet Will
)

How can we do this?

Better if we use foreach()

Thank.

+3
source share
5 answers

If you only need to move the part before the first space (setting $limit = 2to explode()to get only two parts):

function func($n) {
        list($first, $rest) = explode(' ', $n, 2);
        return $rest . ' ' . $first;
} 
$trans = array_map('func', $names);

( Demo )

gives:

Array
(
    [0] => Hood Robin
    [1] => John Little
    [2] => Marion Maid
    [3] => Tuck Friar
    [4] => Scarlet Will
    [5] => Fitzgerald Kennedy John
)
+5
source

Not a particularly glamorous solution:

foreach( $person_array as $key => $value){

$reversed_person_array[]=implode(' ', array_reverse(explode(' ', $value,2)));

}
+3
source
foreach($names as $key => $name)
{
    $splitted = explode(' ', $name, 2);
    $names[$key] = $splitted[1].' '.$splitted[0];
}
+3
+1

! !

I was working on something similar ... got to

$first = $array[0];
array_shift($array);
array_push($array, $first);

then I updated the page and saw yours. Clean and tidy!

0
source

Source: https://habr.com/ru/post/1776195/


All Articles