PHP:获取数组最后一项的最快、最简单的方法是什么?

发布于 2024-08-15 20:54:46 字数 48 浏览 2 评论 0原文

获取数组最后一项的最快、最简单的方法是什么,无论是索引数组、关联数组还是多维数组?

What is the fastest and easiest way to get the last item of an array whether be indexed array , associative array or multi-dimensional array?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

动次打次papapa 2024-08-22 20:54:46
$myArray = array( 5, 4, 3, 2, 1 );

echo end($myArray);

打印“1”

$myArray = array( 5, 4, 3, 2, 1 );

echo end($myArray);

prints "1"

潜移默化 2024-08-22 20:54:46

array_pop()

它从数组末尾删除元素。如果需要保持数组完好无损,可以使用它,然后将值追加到数组的末尾。 $array[] = $popped_val

array_pop()

It removes the element from the end of the array. If you need to keep the array in tact, you could use this and then append the value back to the end of the array. $array[] = $popped_val

走走停停 2024-08-22 20:54:46

试试这个:

$arrayname[count(arrayname)-1]

try this:

$arrayname[count(arrayname)-1]
旧故 2024-08-22 20:54:46

我会说 array_pop 在文档中: array_pop

array_pop — 将元素从数组末尾弹出

I would say array_pop In the documentation: array_pop

array_pop — Pop the element off the end of array

执笔绘流年 2024-08-22 20:54:46

很多很棒的答案。如果您多次执行此操作,请考虑编写一个函数:

function array_top(&$array) {
    $top = end($array);
    reset($array); // Optional
    return $top;
}

或者,根据您的脾气:

function array_top(&$array) {
    $top = array_pop($array);
    $array[] = $top; // Push top item back on top
    return $top;
}

($array[] = ... 优于 array_push() ,参见文档。)

Lots of great answers. Consider writing a function if you're doing this more than once:

function array_top(&$array) {
    $top = end($array);
    reset($array); // Optional
    return $top;
}

Alternatively, depending on your temper:

function array_top(&$array) {
    $top = array_pop($array);
    $array[] = $top; // Push top item back on top
    return $top;
}

($array[] = ... is preferred to array_push(), cf. the docs.)

随风而去 2024-08-22 20:54:46

对于关联数组:

$a= array('hi'=> 'there', 'ok'=> 'then');
list($k, $v) = array(end(array_keys($a)), end($a));
var_dump($k);
var_dump($v);

编辑:也应该适用于数字索引数组

For an associative array:

$a= array('hi'=> 'there', 'ok'=> 'then');
list($k, $v) = array(end(array_keys($a)), end($a));
var_dump($k);
var_dump($v);

Edit: should also work for numeric index arrays

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文