[英]Is there a way with Php to Pop the last element from an array and place it at the beginning?
I was wondering if it's possible with PHP to take the last element of an array and place that element at the beginning of the array.我想知道 PHP 是否可以获取数组的最后一个元素并将该元素放在数组的开头。
When I Print my Array, it says something like this (I took away the whole urls):当我打印我的数组时,它说的是这样的(我拿走了整个网址):
Array (
[0] => /bb-style.css
[1] => /bb-library.css
[2] => /bb-child.css
[3] => /bb-editor-style.css
[4] => /universal.css?cache=1584962088
)
So is there a way to get that last one to the top?那么有没有办法让最后一个到达顶部? I would really appreciate it if someone can tell me the exact code needed, because I often interpret stuff wrong and still can't figure it out when I get an answer.
如果有人能告诉我所需的确切代码,我将不胜感激,因为我经常解释错误,但在我得到答案时仍然无法弄清楚。
Use array_pop() with array_unshift()使用array_pop()和array_unshift()
<?php
// Get and remove last
$last = array_pop($array);
// Insert at beginning
array_unshift($arr , $last);
Array
(
[0] => 5
[1] => 1
[2] => 2
[3] => 3
[4] => 4
)
Array ( [0] => 5 [1] => 1 [2] => 2 [3] => 3 [4] => 4 )
$arr = array("one");
$arr[] = "two";
$arr[] = "three";
print_r($arr); // one, two, three
$last = array_pop($arr); // remove last item ("three")
array_unshift($arr, $last); // add removed item($last = "three") to the begining.
print_r($arr); // three, one, two
You can do it use array_pop() with array_splice() like following :您可以使用 array_pop() 和 array_splice() 来做到这一点,如下所示:
$array = array(1,2,3,4,5,6);
array_splice( $array, 0, 0,array_pop($array));
echo "<pre>";print_r($array);
Output :输出 :
Array
(
[0] => 6
[1] => 1
[2] => 2
[3] => 3
[4] => 4
[5] => 5
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.