【问题标题】:Use comma separated string to create or statements in if else?使用逗号分隔的字符串在 if else 中创建 or 语句?
【发布时间】:2021-02-17 16:18:29
【问题描述】:

目前,我的这段代码运行良好。

if ($ext == 'jpg' or $ext == 'gif' or $ext == 'png' or $ext == 'jpeg' or $ext == 'eps' or $ext == 'pdf') {
  // Extension found execute the rest.
} else {
  // Extension not found show a warning or something.
}

但这就是我所说的硬编码,我希望最终用户能够在此代码所属的组件的设置中更改它。 在这些设置中,我可以很容易地创建一个输入,然后用户需要在一个逗号分隔的列表中填写他们想要的所有扩展名。

在这种情况下:jpg,gif,png,jpeg,eps,pdf

然后将检索这些设置,例如:$ext = $setting_extensions,其中显示字符串 jpg,gif,png,jpeg,eps,pdf

但是如何在这个 if 语句中使用它呢?

我想我可以使用explode和foreach:

$tests = explode(",", $ext);
foreach($tests as $test) {

}

但是如何在 if 语句中使用 or 获取它?

【问题讨论】:

  • explodein_array
  • 这能回答你的问题吗? How to check if an array value exists?
  • @El_Vanja 在收到贡献者的答案并再次阅读您的建议后,我现在可以看到它如何回答我的问题(尽管必须先测试)但在此之前我看不到它是如何适用的.但是感谢您提出问题,因为我在发布之前没有搜索这些关键字。

标签: php


【解决方案1】:

您可以为此使用 in_array。

$tests = explode(",", $setting_extensions);
if (in_array($ext, $tests)) {
   // Extension found execute the rest.
} else {
  // Extension not found show a warning or something.
}

【讨论】:

  • 感谢您的帮助!我将尝试这个以及其他答案,我会接受一个答案 a.s.a.p.
【解决方案2】:

if 语句的条件中使用 PHP 的 in_array() 函数:

$tests = explode(',', $extString);

if (in_array($ext, $tests))) {
    // success
}

但我也会添加一些规范化,因此大小写、间距等不会成为一个因素:

$tests = explode(',', $extString);
$tests = array_map(function($test) {
    return strtolower(trim($test))
}, $tests); 

if (in_array(strtolower($ext), $tests)) {
    // success
}

【讨论】:

  • 感谢您的帮助!我将尝试这个以及其他答案,我会接受一个答案 a.s.a.p.
猜你喜欢
  • 2016-02-11
  • 1970-01-01
  • 2011-06-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多