php - 我想要一个不同的变量来存储通过 stristr 但不能包含除这 3 个不同的东西之外的任何东西

标签 php mysql if-statement strstr

我有以下代码:-

$unitedstatess = stristr($ad['country'], 'united states');
            $unitedkingdom = stristr($ad['country'], 'united kingdom');
            $canada = stristr($ad['country'], 'canada');

            if (($unitedstatess != FALSE) OR ($unitedkingdom != FALSE) OR ($canada != FALSE)) { $adsptc4.=$tempcode; }

如果 $ad['country'] 有美国、英国或加拿大,那么它应该通过,否则如果有除上述之外的不同值,它应该进入其他值。

示例:- 广告 1 具有:( 美国;英国 ) > 那么它应该作为 $adsptc4 传递 广告 2 具有:( United States;italy ) > 那么它应该会失败。

如果您有不明白的地方,请告诉我。

<?
$ad['country'] = "United States;canada";
$allowed = array(
    'united states' => true,
    'united kingdom' => true,
    'canada' => true
);
$countries = strtolower($ad['country']);
$countries = explode(";", $countries);
$found = false;
foreach($countries as $c) {
    if(isset($allowed[$c]) == FALSE) {
        $found = true;
        break;
    }
}
if($found != true) {
    echo "true";
}
else {
    echo "false";
}
?>

效果很好,如果有任何缺点,请告诉我。

最佳答案

您可以将所有“允许”的条目存储在一个数组中。并使用 array_search() 或 isset() 检查它

数组搜索():

$allowed = array('united states', 'united kingdom', 'canada');
$input = strtolower($ad['country']);
if(array_search($input, $allowed) !== false) {
    //your true code
}
else {
    //your else code
}

isset():

$allowed = array(
    'united states' => true,
    'united kingdom' => true,
    'canada' => true
);
$input = strtolower($ad['country']);
if(isset($allowed[$input])) {
    //true
}
else {
    //false
}

要查找条目,它们必须完全相同,因此 $allowed 中的所有条目都是小写,并且您的输入 $ad['country'] 会更改为小写。

这两种选择都是可能的。我更喜欢第二个,因为我可以提供一些可以处理的额外信息(而不是 true,我可以提供一个特殊的数组或其他信息)。

第二次编辑后:

您可以分解给定的国家/地区并检查每个国家:

$countries = strtolower($ad['country']);
$countries = explode(";", $countries);
$found = true;
foreach($countries as $c) {
    $c = trim($c);
    if(!isset($allowed[$c])) {
        $found = false;
        break;
    }
}
if($found == true) {
    //true
}
else {
    //false
}

关于php - 我想要一个不同的变量来存储通过 stristr 但不能包含除这 3 个不同的东西之外的任何东西,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5211096/

相关文章:

C++ 使用 “if else” 和循环迭代的变量计数需要导致零余额

php - db 连接文件是另一个文件,查询在另一个文件中。如何在其中使用 mysqli_query()

php - 使用mysql从三个不同的表中呈现php中的数据

PHP MySQL 使用标签显示相关项目

java - MySQL 查询 "select top 5"查询

mysql - 如何在 SQL 存储过程中打印变量?

Java 输入一个错误的 if 语句

php - 如何从数据库中查找今天和其他日期之间的月份差异?

php - 如何防止从 PHP 到 MYSQL 的多次插入重复条目

java 。我怎样才能提高性能?