我已经研究并尝试了很多关于如何在foreach循环中正确调用函数的解决方案,但我仍然遇到错误。以下是详细信息:
$firstName = "CA";
$firstNameArr = str_split($firstName);
foreach ($firstNameArr as $value){
function getLtr($ltr){
switch ($ltr) :
case "A": return 'The letter is A';
case "B": return 'The letter is B';
case "C": return 'The letter is C';
default: return 'This is not a valid selection';
endswitch;
}
echo getLtr($value) . '<br>';
}
我收到的错误:“无法重新声明getltr()(先前在...引用的第一行函数中声明)”
感谢您的协助!
答案 0 :(得分:4)
你的功能应该在循环之外。
尝试这样的事情:
$firstName = "CA";
$firstNameArr = str_split($firstName);
foreach ($firstNameArr as $value){
echo getLtr($value).'<br>';
}
function getLtr($ltr){
switch ($ltr) :
case "A": return 'The letter is A';
case "B": return 'The letter is B';
case "C": return 'The letter is C';
default: return 'This is not a valid selection';
endswitch;
}
答案 1 :(得分:1)
你没有把这个函数放在循环中,你可以在循环中调用它。
$firstName = "CA";
$firstNamesArray = str_split($firstName);
foreach ($firstNamesArray as $value) {
echo getLetter($value) . '<br>';
}
/**
* The function should be outside the loop.
* When it's inside, it's getting redeclared every time the loop iterates.
*/
function getLetter($letter) {
switch ($letter) :
case "A":
return 'The letter is A';
case "B":
return 'The letter is B';
case "C":
return 'The letter is C';
default:
return 'This is not a valid selection';
endswitch;
}
注意我已经拼写了你的函数名和变量。不要使用这样的缩写。尝试编写自我记录的代码,这意味着函数和变量名称是有意义的,而不是神秘的缩写。
答案 2 :(得分:1)
你把这个函数放在foreach循环之外就是函数的整个点:)
$firstName = "CA";
$firstNameArr = str_split($firstName);
function getLtr($ltr){
switch ($ltr) :
case "A": return 'The letter is A';
case "B": return 'The letter is B';
case "C": return 'The letter is C';
default: return 'This is not a valid selection';
endswitch;
}
foreach ($firstNameArr as $value){
echo getLtr($value) . '<br>';
}