Jason Owens Jason Owens - 4 months ago 13
HTML Question

Can't perform simple array search from array

I have a program that is failing because it's not finding the

$post
in the search of the array, so it's continuing to add each time. I have used the other suggested method of using a
foreach
loop, with
strpos
, such as:
if (strpos($data, $posts) !== false)
, and this will work find the
$post
, but it will also find the rest and run against everything in the data/array. hence why I would just like it to search the array, if it's not there add it, if it is, just say it's there or checking in... I've spent 3 days using
in_array
,
array_search
, etc, now I'm asking for help...

<html>
<body>
<?php
$post = $_POST['name'];
$data = file("data.txt");
if (in_array($post, $data)) {
echo "$post is checking in...";
}
else {
echo "Adding to $data...";
$data = fopen("data.txt", "a+");
fwrite($data, $post.PHP_EOL);
fclose($data);
}
$data = file("data.txt");
foreach ($data as $d) {
echo $d;
}

?>

</body>
</html>


tclient.html

<html>
<body>

<form action="test4.php" method="POST">
Name: <input type="text" name="name"><br>
<input type="submit">
</form>

</body>
</html>


data.txt

Names
John
Doe

Answer

The value in $post probably doesn't have a new line at the end. You can specify not to include new lines when you use file().

file("data.txt", FILE_IGNORE_NEW_LINES);