2013-12-12 46 views
0

我已經研究並嘗試了很多解決方案,如何在foreach循環中正確調用函數,而且我仍然收到錯誤。以下是詳細內容:如何正確構建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

你不能把一個函數定義一個循環 – GordonM

回答

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; 
} 

注意我已經說明了你的函數名和變量。不要使用那樣的縮寫。嘗試編寫自我記錄的代碼,這意味着函數和變量名稱是有意義的,而不是隱含的縮寫。

+0

內謝謝你的回答和對其他意見的整點自我記錄(因此你是被選中的答案)!我對編碼相當陌生,而且我試圖從其他晦澀難懂的例子中學習。 – user1713438

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

你把函數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>'; 
    } 
+0

謝謝,你可以告訴我,我是一個新手在編碼:) – user1713438