從 PHP 的函式返回兩個值


兩個變數無法顯式返回,它們可以放入列表/陣列資料結構中並返回。

示例

 即時演示

function factors( $n ) {
   // An empty array is declared
   $fact = array();
   // Loop through it
   for ( $i = 1; $i < $n; $i++) {
      // Check if i is the factor of
      // n, push into array
      if( $n % $i == 0 )
      array_push( $fact, $i );
   }
   // Return array
   return $fact;
}
// Declare a variable and initialize it
$num = 12;
// Function call
$nFactors = factors($num);
// Display the result
echo 'Factors of ' . $num . ' are: <br>';
foreach( $nFactors as $x ) {
   echo $x . "<br>";
}

輸出

這將生成以下輸出 −

Factors of 12 are:
1
2
3
4
6

更新於:2020 年 4 月 7 日

753 次瀏覽

啟動你的職業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.