【问题标题】:Check if 2 values are in an array in php检查 2 个值是否在 php 的数组中
【发布时间】:2016-06-17 10:06:59
【问题描述】:

全部!

所以,我有这个代码:

<?php
$clienthwid = $_POST["clienthwid"];
$clientip = $_POST["clientip"];
$hwid_logs = "hwid_log.txt";
$ip_logs = "ip_log.txt";
$handle_ip = fopen($ip_logs, 'a') or die("404 file not found");
$handle_hwid = fopen($hwid_logs, 'a') or die("404 file not found");
$client_whitelist = array (
    // put hwids and ip here
    "hwid" => "123456789", "12345678",
    "ip" => "123.456.789", "123.456.788",
);
//check if client hwid or ip is in the array
if (in_array($clienthwid, $client_whitelist)) {
    echo "TRUE";
    fwrite($handle_hwid, $clienthwid."\n");
    fwrite($handle_ip, $clientip."\n");
} else {
    echo "FALSE";
    fwrite($handle_hwid, $clienthwid."\n");
    fwrite($handle_ip, $clientip."\n");
}
?>

所以,对于

in_array($clienthwid, $client_whitelist);

我想知道怎么做

in_array($clienthwid and $clientip, $client_whitelist)

如何检查两个变量是否在一个数组中?

【问题讨论】:

  • 您的客户端白名单数组的格式是否正确?它不应该有子数组来分组 hwid 和 ip 值吗?
  • this的可能重复
  • in_array multiple values的可能重复

标签: php arrays


【解决方案1】:

只需使用两个in_array 语句。

in_array($clienthwid, $client_whitelist) && in_array($clientip, $client_whitelist)

仅当 两者 都在 $client_whitelist 中时才会如此。 如果您想确定至少 on 是否在其中,请使用 || 或运算符。

//check if client hwid or ip is in the array
if (in_array($clienthwid, $client_whitelist) || in_array($clientip, $client_whitelist)) {
    echo "TRUE";
    fwrite($handle_hwid, $clienthwid."\n");
    fwrite($handle_ip, $clientip."\n");
} else {
    echo "FALSE";
    fwrite($handle_hwid, $clienthwid."\n");
    fwrite($handle_ip, $clientip."\n");
}

【讨论】:

  • 谢谢,我是 php 新手!
【解决方案2】:

使用 array_intersect

$array = array("AA","BB","CC","DD");
$check1 = array("AA","CC");
$check2 = array("EE","FF");

if(array_intersect($array, $check1)) {
    echo "Exist";
}else{
    echo "Not exist"; 
}

if(array_intersect($array, $check2)) {
    echo "Exist";
}else{
    echo "Not exist"; 
}

参考:3v4l

【讨论】:

    【解决方案3】:

    下面的函数将检查是否所有给定的项目都在目标数组中。它使用了 foreach,而且相当简单。

    if (multiple_in_array(array('onething', 'anotherthing'), $array)) {
        // 'onething' and 'anotherthing' are in array
    }
    
    function multiple_in_array($needles = array(), $haystack = array())
    {
        foreach ($needles as $needle) {
            if (!in_array($needle, $haystack)) {
                return false;
            }
        }
        return true;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-06-22
      • 1970-01-01
      • 1970-01-01
      • 2022-01-07
      • 2021-01-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多