【问题标题】:how to rewrite this php "if" statement without the deprecated "each" function?如何在没有弃用的“each”函数的情况下重写这个 php“if”语句?
【发布时间】:2020-07-01 02:46:14
【问题描述】:

如何重写这段 php 脚本,使其不再在 'if' 语句中使用已弃用的函数 'each'?

if (list($_basic_auth_realm, $_basic_auth_header) = each($_auth_creds))
{
     ...
}

很多谢谢。供您输入!

V.

[编辑]。此 if 语句不在循环中。它是更大区块的一部分:

if (!empty($_basic_auth_header))
    {
    ....
    }
    else if (!empty($_basic_auth_realm) && isset($_auth_creds[$_basic_auth_realm]))
    {
    ....
    }
    else if (list($_basic_auth_realm, $_basic_auth_header) = each($_auth_creds))
    {
    ....
    }

$_basic_auth_realm, $_basic_auth_header 是字符串 $_auth_creds 是一个数组

我真的不明白这个“if”语句是如何工作的。我只尝试更新执行时返回警告的脚本。正如 Abdullah Arif 所写,它在我的 NAS 上用作 php 代理:https://github.com/emersion/phproxy

【问题讨论】:

  • 这是循环吗?使用foreach
  • 首先,您需要了解 [each][1] 的作用。然后你需要用类似的逻辑替换它。这实际上取决于$_basic_auth_realm$_basic_auth_header$_auth_creds 中的内容,以及if 语句的意图。 [1]:php.net/manual/en/function.each.php
  • 谢谢丹尼尔。在网上找到的大多数带有“each”语句的样本确实都在“while”循环中。就我而言,我在 Synology 的一个包中找到了这个 php 脚本(由 Abdullah Arif 于 2007 年制作)。我希望有一种方法可以在没有循环的情况下重写它。老实说,使用 list (x, y) = each( my_array ) 有点奇怪......我猜如果 my_array 没有长度,它会返回 false != 2

标签: php each


【解决方案1】:

使用您自己的变量来跟踪数组中的当前索引,而不是依赖于数组的内部状态。

$auth_creds_index = 0;
...
    else if (list($_basic_auth_realm, $_basic_auth_header) = $_auth_creds[$auth_creds_index++])

您当前使用each($_auth_creds) 的每个地方都应该使用$_auth_creds[$auth_creds_index++],它们将获得数组的连续元素。

如果使用新数组重新分配变量,则需要将变量重置回0

您还可以为自动执行所有这些操作的数组定义一个类包装器。

【讨论】:

  • Thx Barmar,我在我的问题中添加了评论。 if 语句不在循环中。我可以重写块以使用循环,但希望在单个语句中包含一些内容。
猜你喜欢
  • 2011-03-28
  • 2019-03-06
  • 1970-01-01
  • 2012-08-23
  • 2018-10-25
  • 1970-01-01
  • 2013-01-23
  • 1970-01-01
  • 2022-01-08
相关资源
最近更新 更多