为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
冉冉说 2022-08-19 16:33:04
我正在尝试用最后一个元素反转函数参数中给出的数组的第一个元素。这是我到目前为止的尝试:$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。提前致谢!
查看完整描述

3 回答

?
慕后森

TA贡献1802条经验 获得超5个赞

有几种方法可以做到这一点,问题是你的代码在存储它并尝试移动它之前覆盖了开始。此代码采用该值,然后覆盖它,然后更新最后一项...


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

这假定使用数字索引数组,而不是任何其他形式的索引。


查看完整回答
反对 回复 2022-08-19
?
蛊毒传说

TA贡献1895条经验 获得超3个赞

此函数将第一个元素与数组的最后一个元素交换。


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

此函数适用于数字数组和关联数组。密钥保留,仅交换值。


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



查看完整回答
反对 回复 2022-08-19
?
慕姐8265434

TA贡献1813条经验 获得超2个赞

您可以移动第一个元素并弹出最后一个元素并存储它们,然后取消移动最后一个元素并按下第一个元素


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


查看完整回答
反对 回复 2022-08-19
  • 3 回答
  • 0 关注
  • 117 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号