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

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


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


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


如您所见,0 与 4 反转,但 4 与 0 不反转。提前致谢!


一只斗牛犬
浏览 128回答 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);这假定一个数字索引数组,而不是任何其他形式的索引。

开心每一天1111

此函数将第一个元素与数组的最后一个元素交换。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) }

呼啦一阵风

您可以移动第一个元素并弹出最后一个并存储它们,然后取消移动最后一个并推送第一个$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