请看一下这段代码:
$end = isset($newvar) ? array($newvar) : null;
while($ends = array_shift($end)){
  ...
当我使用 PHP 7.2 时运行良好,但升级到 8.1 后,它抛出:
PHP 致命错误:未捕获类型错误:array_shift():参数 #1 ($array) 必须是数组类型,在 /path/to/qanda.php:469 中给出 null
知道如何修复它吗?
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
最基本的解决方案是将
null值替换为空数组,以符合类型要求:$end = isset($newvar) ? array($newvar) : []; while($ends = array_shift($end)){您还可以创建数组并在
$newvar上使用空合并运算符:$end = [$newvar ?? null]; while($ends = array_shift($end)){但我不明白为什么您要创建一个具有单个值的数组,然后使用
array_shift的返回值创建一个循环。循环体只会运行一次。 也许只是使用一个条件?if (isset($newvar)) {只需使用空数组即可:
array_shift 将在第一次调用时返回
null空数组作为输入,因此循环不会执行。