我有一个程序失败了,因为它在数组的搜索中找不到$post
,所以每次都在继续添加。我使用了另一种建议的方法,即使用foreach
循环和strpos
,例如:if (strpos($data, $posts) !== false)
,这将找到$post
,但它也将找到其余部分,并针对数据/数组中的所有内容运行。因此,为什么我只想让它搜索数组,如果它不在那里,添加它,如果它在那里,就说它在那里或签入…我已经用了3天的in_array
、array_search
等,现在我正在寻求帮助。。。
<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
$post
中的值可能在末尾没有新行。使用file()
时,可以指定不包含新行。
file("data.txt", FILE_IGNORE_NEW_LINES);