我有一个PHP代码。但是,当我echo
时,页面上什么也没打印。
有人可以帮助我吗?
public function checkcharacter(Request $request)
{
$woord = str_split($request->session()->get('woord'));
foreach ($woord as $letter) {
if ($request->letter === $letter) {
// return view('hangman')->getData (['goed', 'goed gedaan' =>$woord]); // =>$dottedword
return view('hangman')->with (['woord' => $woord, 'correct' => 'fout']);
}
else {
echo "wrong answer!";
}
}
}
答案 0 :(得分:1)
如果我对您的理解正确,并且您想只获得一次wrong answer!
字符串(如果后者不相同),则需要使用break;
构造。
public function checkcharacter(Request $request)
{
$woord = str_split($request->session()->get('woord'));
foreach ($woord as $letter) {
if ($request->letter !== $letter) {
echo "wrong answer!";
break;
}
// return view('hangman')->getData (['goed', 'goed gedaan' =>$woord]); // =>$dottedword
return view('hangman')->with(['woord' => $woord, 'correct' => 'fout']);
}
}
希望我能以正确的方式理解您的问题。
更新了1.0
如果您不想打破循环,那么我有第二种解决您的问题的方法:
public function checkcharacter(Request $request)
{
$woord = str_split($request->session()->get('woord'));
$isCorrect = true;
foreach ($woord as $letter) {
if ($request->letter !== $letter) {
$isCorrect = false;
}
// return view('hangman')->getData (['goed', 'goed gedaan' =>$woord]); // =>$dottedword
return view('hangman')->with(['woord' => $woord, 'correct' => 'fout']);
}
if (!$isCorrect) {
echo 'wrong answer!';
}
}
答案 1 :(得分:0)
以下else块应该在foreach块之外
else {
echo "wrong answer!";
}
因此,假设条件是否成功,则流程将返回而没有任何回声。我没有运行此代码段。请在最后检查它。
public function checkcharacter(Request $request)
{
$woord = str_split($request->session()->get('woord'));
foreach ($woord as $letter) {
if ($request->letter === $letter) {
// return view('hangman')->getData (['goed', 'goed gedaan' =>$woord]); // =>$dottedword
return view('hangman')->with (['woord' => $woord, 'correct' => 'fout']);
}
}
// if answer is not found then will give the following echo once.
echo "wrong answer!";
}
答案 2 :(得分:0)
如果您只想检查字母是否在单词中,就不需要循环,只需检查字母是否在单词中-我使用strpos()
public function checkcharacter(Request $request)
{
if ( strpos ($request->letter, $request->session()->get('woord')) !== false) {
return view('hangman')->with (['woord' => $woord, 'correct' => 'fout']);
}
else {
return view('hangman')->with (['woord' => $woord, 'correct' => 'false']);
}
}
请注意,两个分支都返回一个视图-未找到字母的第二个视图设置了'correct' => 'false'
,您可能需要更改此视图以适合您的需求。