You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP 8.0中如何将已废弃的each()函数替换为foreach()?

PHP 8.0 废弃each()后的代码修复方案

PHP 8.0 已移除each()函数,原代码中list($orig,$values) = each($where);这一行会触发致命错误:Uncaught Error: Call to undefined function each()。以下是替换为foreach()后的完整修复代码:

public function getMetaboxConfig($type) {
    static $cache;

    if (!empty($cache[$type])) {
        return $cache[$type];
    }

    do_action("pe_theme_metabox_config_$type");

    $config =& PeGlobal::$config;
    $metaboxes = PeGlobal::$config["metaboxes"];

    $pmboxes = empty($config["metaboxes-$type"]) ? null : $config["metaboxes-$type"];

    if ($custom = apply_filters("pe_theme_metabox_$type",$pmboxes)) {
        foreach ( $custom as $key => $value ) {
            $metaboxes[$key] = $custom[$key];
            $where =& $metaboxes[$key]["where"];
            
            // 替换废弃的each(),获取数组第一个键值对
            foreach ($where as $orig => $values) {
                break; // 仅循环一次,匹配原each()的行为
            }
            
            if ($orig != $type) {
                unset($where[$orig]);
                $where[$type] = $values;
            }
        }
    }
    $cache[$type] = $metaboxes;
    return $metaboxes;
}

修复说明

  • 原代码中each()用于获取数组的第一个键值对,这里用带break的foreach循环实现相同逻辑
  • 保留原代码所有业务逻辑,仅替换废弃函数部分,确保功能完全一致
  • 该写法兼容PHP 7.2+及PHP 8.x全版本

内容的提问来源于stack exchange,提问作者Ed_B

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 13:30:43