PHP报错:Trying to access array offset on value of type null 求解
解决PHP数组偏移访问null值的Notice报错
问题原因
这两条Notice报错的核心是:代码尝试访问null类型值的数组偏移(即$row["term_id"]部分),说明执行到对应行时$row变量为null,而非预期的数组结构。
解决方案
根据业务需求,可选择以下两种修复方式:
1. 跳过无效的$row数据
如果没有有效的term_id就不需要生成对应标签,直接在代码块前增加校验,确保$row是有效数组且包含term_id键:
修复后的第一处代码:
<?php // 先校验$row的有效性 if ($row && isset($row["term_id"])) { $html .= '<a class="'; if ($first) $html .= 'active'; $html .= '" href="#class-' . $row["term_id"] . '" data-toggle="tab" aria-expanded="'; $html .= ($first) ? 'true' : 'false'; $first = false; $html .= '"> <h3>Year ' . $year . '</h3> </a><div><ul>'; } ?>
第二处代码同理修改:
<?php if ($row && isset($row["term_id"])) { $html .= ' <a class="'; if ($first) $html .= 'active'; $html .= '" href="#class-' . $row["term_id"] . '" data-toggle="tab" aria-expanded="'; $html .= ($first) ? 'true' : 'false'; $first = false; $html .= '"> <h4>Starting in ' . $month_name . '</h4> </a><div><ul>'; } ?>
2. 给缺失的term_id设置默认值
如果即使$row无效也要生成标签,使用PHP的null合并运算符(??)给term_id设置默认值,避免报错:
修改第一处的$row["term_id"]部分:
$html .= '" href="#class-' . ($row["term_id"] ?? 'default-class') . '" data-toggle="tab" aria-expanded="';
第二处同样修改:
$html .= '" href="#class-' . ($row["term_id"] ?? 'default-class') . '" data-toggle="tab" aria-expanded="';
额外排查建议
可以回溯$row的来源(比如数据库查询、函数返回值),确认为什么会出现null值——比如是否存在查询结果为空、循环遍历到无效数据等情况,从根源上避免无效数据进入这段代码逻辑。
内容的提问来源于stack exchange,提问作者KSU Community and Professional
相关产品推荐
相关产品推荐

