kazu
kazu

Reputation: 21

reverse first array element with last

I'm trying to reverse first element of array given in parameter of my function with last element.

here is my try so far:

$my_array = [0, 1, 2, 3, 4];


function  reverse_start_with_last(array &$arr)
{
    $arr[0] = end($arr);

    $last = end($arr);

    $last = reset($arr);

    print_r($arr);

    static $callingnumber = 0;
    $callingnumber++;

    echo '<br><br>' .     $callingnumber;
}

reverse_start_with_last($my_array);

it outputs:

Array ( [0] => 4 [1] => 1 [2] => 2 [3] => 3 [4] => 4 ).

so as you can see zero is reversed with 4 but 4 is not reversed with 0.. Thanks in advance !

Upvotes: 2

Views: 438

Answers (3)

Rain
Rain

Reputation: 3926

You can shift the first element and pop the last and store them and then unshift the last and push the first

$my_array = [0, 1, 2, 3, 4];

function  reverse_start_with_last(array &$arr)
{
    $first = array_shift($arr); // remove the first element and store it
    $last = array_pop($arr); // remove the last and store it
    array_unshift($arr, $last); // add the last at the beginning of the array
    array_push($arr, $first); // add the first at the end of the array
}


reverse_start_with_last($my_array);
print_r($my_array)

Upvotes: 0

jspit
jspit

Reputation: 7683

This function swap the first with the last element of the array.

function  array_change_first_last(array &$arr)
{
    $last = end($arr);
    $arr[key($arr)] = reset($arr);
    $arr[key($arr)] = $last;
}

$my_array = [0, 1, 2, 3, 4];
array_change_first_last($my_array);

This function works with numeric and associative arrays alike. The keys remain, only the values ​​are exchanged.

$ass_array = ['a' => 0, 'b' => 1, 'c' => 2, 'd' => 3, 'z'=> 4];
array_change_first_last($ass_array);

Result:

array(5) { ["a"]=> int(4) ["b"]=> int(1) ["c"]=> int(2) ["d"]=> int(3) ["z"]=> int(0) }

Upvotes: 1

Nigel Ren
Nigel Ren

Reputation: 57121

There are a few ways to do it, the problem is that your code overwrites the start before it stores it and tries to move it. This code takes the value, then overwrites it and then updates the last item...

function  reverse_start_with_last(array &$arr)
{
    $first = $arr[0];
    $arr[0] = end($arr);
    $arr[count($arr)-1] = $first;
    print_r($arr);
}

reverse_start_with_last($my_array);

This assumes a numerically indexed array and not any other form of indexing.

Upvotes: 3

Related Questions