我在玩一个基本的PHP网站,只是为了我自己的知识,我基本上有一个文本文件,里面装满了"密码";。我已经在页面中以数组的形式打开了这个文本文件,但当我搜索特定元素时,唯一显示为有效的密码是最后一个选项,它似乎忽略了数组中的所有其他元素。
所以如果我的密码列表是
密码
12345
测试
qwerty
当我搜索前3个元素时,它表示它不存在于数组中。但是,如果我在这里搜索最后一个值"qwerty",它就会匹配。
<?php
$file = explode("'n", file_get_contents("passwords.txt"));
//Call the function and pass in the list
if (isset($_POST['submit_login'])) {
//Set the search variable
$search = $_POST['password'];
search_array($file, $search);
} else {
//echo "You did not search! <br />";
//echo "<a href='searchForm.html'>Try again?</a>";
}
function search_array($array_value, $search_query)
{
echo "<span><h4>The Array List: </h4><span/>";
foreach ($array_value as $key => $value) {
echo $key." ";
echo $value."<br />";
}
if ($value == $search_query) {
echo "<h5>Search Stuff</h5>";
echo "You searched for: " . $search_query . "</br>";
echo "Your search was found in the index #" .$key. "<br />";
} else {
echo "You searched for: " . $search_query . "</br>";
echo "Your search did not match any of the items. <br />";
echo "<a href='searchForm.html'>Try again?</a>";
}
}
?>
然而,例如,如果我搜索"12345",即数组中的索引1,我将获得输出
您搜索的是:12345
您的搜索与任何项目都不匹配。
但是,搜索最后一个元素"qwerty"会得到所需的响应。
您的if ($value == $search_query)
不在foreach循环中。如果else挡住了,将foreach的闭合括号移到下面,它应该可以工作。
不要让一切都变得如此复杂,只需使用以下内容:
(在这里,我首先用file()
读取您的文件。然后只需使用array_search()
查看值是否在数组中,并获取密钥)
<?php
$lines = file("passwords.txt", FILE_IGNORE_NEW_LINES)
//Call the function and pass in the list
if (isset($_POST['submit_login'])) {
//Set the search variable
$search = $_POST['password'];
search_array($lines, $search);
} else {
//echo "You did not search! <br />";
//echo "<a href='searchForm.html'>Try again?</a>";
}
function search_array($array_value, $search_query) {
echo "<span><h4>The Array List: </h4><span/>";
if(($key = array_search($search_query, $array_value)) !== FALSE) {
echo "<h5>Search Stuff</h5>";
echo "You searched for: " . $search_query . "</br>";
echo "Your search was found in the index #" .$key. "<br />";
} else {
echo "You searched for: " . $search_query . "</br>";
echo "Your search did not match any of the items. <br />";
echo "<a href='searchForm.html'>Try again?</a>";
}
}
?>
尝试将"search_array"方法更改为此方法。
function search_array($array_value, $search_query)
{
echo "<span><h4>The Array List: </h4><span/>";
$match = false;
foreach ($array_value as $key => $value) {
echo $key." ";
echo $value."<br />";
if ($value == $search_query) {
$match = true;
break;
}
}
if ($match) {
echo "<h5>Search Stuff</h5>";
echo "You searched for: " . $search_query . "</br>";
echo "Your search was found in the index #" .$key. "<br />";
} else {
echo "You searched for: " . $search_query . "</br>";
echo "Your search did not match any of the items. <br />";
echo "<a href='searchForm.html'>Try again?</a>";
}
}
密码检查应该在foreach循环中,检查后可以打印一些内容。