I have a following script, which I use to generate participation list. The idea is that people can submit their names to the list on a web page. Submitting names works fine, but the problems occur when trying to check whether the typed name is already on the list or not. It seems that function in_array() returns false ALWAYS. Same problem naturally occurs when trying to delete a name from the list.
The file parts.txt builds up as it should, for example
George
John
Jerry
Ted
I would appreciate SO MUCH if someone finds error(s) and could explain why in_array() returns false, even if the name was already on the list! I have googled and read manuals for two days now and I'm out of explanations...
<?php
if($_POST['name1']) {
$parts = file("parts.txt");
$name = $_POST['name1'];
$pswd = $_POST['password'];
if ($pswd == "test" && $_POST['Register']) {
if (in_array($name, $parts)) {
echo "<p class=\"error\">Error: Name was was already on the list!<br></p>";
exit;
}
$tt = fopen("parts.txt", "a");
fwrite($tt, "$name\n");
fclose($tt);
}
elseif ($pswd == "test" && $_POST['Unregister']) {
if (in_array($name, $parts)) {
for ($i=0; $i < count($parts); $i++) {
if ($parts[$i] == $name) {
unset($parts[$i]);
}
}
$parts = array_values($parts);
file_put_contents("parts.txt",implode($parts));
}
else {
echo "<p class=\"error\">Error: Name was not on the list!<br></p>";
}
}
else {
echo "<p class=\"error\">Error: Password incorrect!<br></p>";
}
}
?>
Mysterious problem with in_array
Moderator: General Moderators
Re: Mysterious problem with in_array
Use code tags when posting code.
Next, file() when used in the same context that you used it... leaves newlines on each element. You'll need to strip off the newlines. http://www.php.net/file/ for more information.
Next, file() when used in the same context that you used it... leaves newlines on each element. You'll need to strip off the newlines. http://www.php.net/file/ for more information.