请帮我把这个伪代码翻译成真正的php代码:

 foreach ($arr as $k => $v)
    if ( THIS IS NOT THE LAST ELEMENT IN THE ARRAY)
        doSomething();

编辑:数组可以有数字键或字符串键

推荐答案

你可以使用PHP的end()

$array = array('a' => 1,'b' => 2,'c' => 3);
$lastElement = end($array);
foreach($array as $k => $v) {
    echo $v . '<br/>';
    if($v == $lastElement) {
         // 'you can do something here as this condition states it just entered last element of an array'; 
    }
}

Update1

正如@mijoja所指出的,如果您在数组中多次使用相同的值,则上面可能会有问题.下面是它的修复方法.

$array = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 2);
//point to end of the array
end($array);
//fetch key of the last element of the array.
$lastElementKey = key($array);
//iterate the array
foreach($array as $k => $v) {
    if($k == $lastElementKey) {
        //during array iteration this condition states the last element.
    }
}

Update2

我发现@onteria_uu的解决方案比我的答案更好,因为它不会修改数组内部指针,我正在更新答案以匹配他的答案.

$array = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 2);
// Get array keys
$arrayKeys = array_keys($array);
// Fetch last array key
$lastArrayKey = array_pop($arrayKeys);
//iterate array
foreach($array as $k => $v) {
    if($k == $lastArrayKey) {
        //during array iteration this condition states the last element.
    }
}

谢谢你@onteria_

Update3

As pointed by @CGundlach PHP 7.3 introduced array_key_last which seems much better option if you are using PHP >= 7.3

$array = array('a' => 1,'b' => 2,'c' => 3);
$lastKey = array_key_last($array);
foreach($array as $k => $v) {
    echo $v . '<br/>';
    if($k == $lastKey) {
         // 'you can do something here as this condition states it just entered last element of an array'; 
    }
}

Php相关问答推荐

无法使用PHP DomDocument找到IMG元素

邮箱打开跟踪器不工作时发送邮件使用laravel调度程序

为什么调用干预\映像引发错误驱动程序\GD\Driver not found?

与会者在WooCommerce中按购物车项目数量自定义 checkout 字段

Laravel;Composer安装突然返回选项快捷方式不能为空.

允许在WooCommerce管理员优惠券列表中显示自定义优惠券类型

如何将隐式乘法添加到PHPPEG基本计算器语法中?

文本到语音:不考虑音高值

允许在WooCommerce管理订单列表中使用计费邮箱进行搜索

如何在自定义邮箱内容中获取WooCommerce订单项目的详细信息?

主机中未检索用户表数据

Woocommerce 中为空时隐藏显示变体自定义字段数据

为什么 php 只能在我的 Nginx Web 服务器的某些目录中工作?

使用动态地址和动态文件创建zip文件并获取zip文件链接

在shopware 6.5上可以使用什么事件来判断刚刚支付的订单的状态

跟踪通过 WooCommerce 分层定价表插件进行的购买

如何通过帖子自定义元数据进行查询

如何在构建 PHP 类别数组树的递归函数中将父面包屑传递给子项?

同一页面上多个组件的 Livewire 分页问题

MySQLI bind_param导致的Cannot modify readonly property错误