如果用户在php中的数组中,则写入日志

Ryf*_*lex -2 php arrays foreach

任何人都可以解释为什么以下不起作用?

我想写Blocked userlog.txt,如果$user是数组中$blockedusers

$blockedusers = array("USER1", "USER2");
$user = "USER1";
foreach ($user as $blockedusers) {
    $file = 'log.txt';
    $current = file_get_contents($file);
    $current .= 'Blocked user' . "\n";
    file_put_contents($file, $current);
}
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

Ama*_*ali 10

如果您只想检查特定用户是否在$blockedusers数组中,则不需要循环.为此目的有一个内置函数,建议使用它.

使用in_array():

if (in_array($user, $blockedusers)) {
    $current = file_get_contents($file);
    $current .= 'Blocked user: '.$user."\n";
    file_put_contents($file, $current);
}
Run Code Online (Sandbox Code Playgroud)

或者,如果您有一组用户,并且想要检查其中是否有任何用户位于阻止列表中,则可以执行以下操作:

$users = array('foo', 'bar', 'baz');
foreach ($users as $user) {
    if (in_array($user, $blockedusers)) {
        $current = file_get_contents($file);
        $current .= 'Blocked user' . "\n";
        file_put_contents($file, $current);
    }
}
Run Code Online (Sandbox Code Playgroud)