Mysterious problem with in_array
Posted: Mon Oct 05, 2009 3:41 pm
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>";
}
}
?>
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>";
}
}
?>