Can anyone explain why the following isn't working?
I want to write Blocked user
to log.txt
if $user
is in the array $blockedusers
$blockedusers = array("USER1", "USER2");
$user = "USER1";
foreach ($user as $blockedusers) {
$file = 'log.txt';
$current = file_get_contents($file);
$current .= 'Blocked user' . "
";
file_put_contents($file, $current);
}
Any ideas?
A loop is not required if you just want to check if a particular user is in the $blockedusers
array. There's a built-in function for that purpose and it's recommended to use that.
Using in_array()
:
if (in_array($user, $blockedusers)) {
$current = file_get_contents($file);
$current .= 'Blocked user: '.$user."
";
file_put_contents($file, $current);
}
Or, if you have an array of users, and you want to check if any of them are in the blocked list, you can do the following:
$users = array('foo', 'bar', 'baz');
foreach ($users as $user) {
if (in_array($user, $blockedusers)) {
$current = file_get_contents($file);
$current .= 'Blocked user' . "
";
file_put_contents($file, $current);
}
}