Mysterious problem with in_array

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Oxxi
Forum Newbie
Posts: 1
Joined: Mon Oct 05, 2009 3:17 pm

Mysterious problem with in_array

Post by Oxxi »

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>";
}
}
?>
User avatar
Mirge
Forum Contributor
Posts: 298
Joined: Thu Sep 03, 2009 11:39 pm

Re: Mysterious problem with in_array

Post by Mirge »

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.
Post Reply