反转第一个数组元素和最后一个数组元素

我正在尝试用最后一个元素反转函数参数中给出的数组的第一个元素。


这是我到目前为止的尝试:


$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);

它输出:


数组 ( [0] => 4 [1] => 1 [2] => 2 [3] => 3 [4] => 4 )。


所以正如你所看到的,零被反转为4,但4不被反转为0。提前致谢!


冉冉说
浏览 118回答 3
3回答

慕后森

有几种方法可以做到这一点,问题是你的代码在存储它并尝试移动它之前覆盖了开始。此代码采用该值,然后覆盖它,然后更新最后一项...function&nbsp; reverse_start_with_last(array &$arr){&nbsp; &nbsp; $first = $arr[0];&nbsp; &nbsp; $arr[0] = end($arr);&nbsp; &nbsp; $arr[count($arr)-1] = $first;&nbsp; &nbsp; print_r($arr);}reverse_start_with_last($my_array);这假定使用数字索引数组,而不是任何其他形式的索引。

蛊毒传说

此函数将第一个元素与数组的最后一个元素交换。function&nbsp; array_change_first_last(array &$arr){&nbsp; &nbsp; $last = end($arr);&nbsp; &nbsp; $arr[key($arr)] = reset($arr);&nbsp; &nbsp; $arr[key($arr)] = $last;}$my_array = [0, 1, 2, 3, 4];array_change_first_last($my_array);此函数适用于数字数组和关联数组。密钥保留,仅交换值。$ass_array = ['a' => 0, 'b' => 1, 'c' => 2, 'd' => 3, 'z'=> 4];array_change_first_last($ass_array);结果:array(5) { ["a"]=> int(4) ["b"]=> int(1) ["c"]=> int(2) ["d"]=> int(3) ["z"]=> int(0) }

慕姐8265434

您可以移动第一个元素并弹出最后一个元素并存储它们,然后取消移动最后一个元素并按下第一个元素$my_array = [0, 1, 2, 3, 4];function&nbsp; reverse_start_with_last(array &$arr){&nbsp; &nbsp; $first = array_shift($arr); // remove the first element and store it&nbsp; &nbsp; $last = array_pop($arr); // remove the last and store it&nbsp; &nbsp; array_unshift($arr, $last); // add the last at the beginning of the array&nbsp; &nbsp; array_push($arr, $first); // add the first at the end of the array}reverse_start_with_last($my_array);print_r($my_array)
打开App,查看更多内容
随时随地看视频慕课网APP