Search code examples
phparraysforeachswapcpu-word

Swap position of words in an array of 2-word elements


We have array with names:

[
    'Robin Hood',
    'Little John',
    'Maid Marion',
    'Friar Tuck',
    'Will Scarlet'
]

First word inside each item should be moved to the end of this item.

We should get this:

[
    'Hood Robin',
    'John Little',
    'Marion Maid',
    'Tuck Friar',
    'Scarlet Will'
]

Solution

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

    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
    )