【问题标题】:How to check if multiple numbers are in a comma-separated string? [duplicate]如何检查多个数字是否在逗号分隔的字符串中? [复制]
【发布时间】:2021-07-24 22:27:11
【问题描述】:

我有这样的代码:

<?php  
$kecuali = "6,8,9";
for ($x = 0; $x < 15; $x++) {
  if ($x == $kecuali) {
    continue;
  }
  echo "The number is: $x <br>";
}
?>

这样的结果

The number is: 0
The number is: 1
The number is: 2
The number is: 3
The number is: 4
The number is: 5
The number is: 7
The number is: 8
The number is: 9
The number is: 10
The number is: 11
The number is: 12
The number is: 13
The number is: 14

为什么数字 8 和 9 仍然在结果中,而不是数字 6?我该如何解决这个问题,以便所有 3 个数字都不会出现在结果中?

【问题讨论】:

  • $kecuali 是一个字符串伙伴。而是检查为in_array($x,explode(",",$kecuali))。您还可以缓存爆炸部分。
  • 哇,谢谢兄弟,你解决了我的问题。

标签: php arrays string for-loop


【解决方案1】:

== 应该避免;它试图在运行等价测试之前强制类型。所以"6fjsdkjfds" == 6 恰好是真的,因为前导"6" 在比较之前被转换为一个数字:(int)"6fjsdkjfds" =&gt; 6

请始终使用===

现在,此更改进一步破坏了您的代码,似乎是朝着错误方向迈出的一步。但那是因为使用您的一组数字作为数组并使用in_array(或array_key_exists,如果您希望使用键而不是值的 O(1) 查找时间...)执行查找是测试成员资格的正确方法,不扫描字符串或使用=====

请尝试:

<?php

$skip = [6, 8, 9];

for ($i = 0; $i < 15; $i++) {
    if (in_array($i, $skip)) {
        continue;
    }

    echo "The number is: $i<br>";
}

?>

如果$skip(或$kecuali)不是您可以控制的数据,您可能需要将其解析为一个数组:

$skip = array_map("intval", explode(",", $kecuali));

在上述代码之前。

如果您有大型数组,请考虑将复杂性提高到 O(n+m) 而不是 O(n*m)

<?php

$skip = [6, 8, 9];
$skip = array_flip($skip);

for ($i = 0; $i < 15; $i++) {
    if (array_key_exists($i, $skip)) {
        continue;
    }

    echo "The number is: $i<br>";
}

?>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-06
    • 2018-06-26
    • 1970-01-01
    • 2012-11-12
    • 2021-09-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多