当前位置:Gxlcms > PHP教程 > PHP接收不到函数返回值

PHP接收不到函数返回值

时间:2021-07-01 10:21:17 帮助过:15人阅读

for ($i = 0; $i < 30; $i++) {
$arr[$i] = $i;
}

var_dump(BinarySearch($arr, 100, 0, count($arr) - 1));


function BinarySearch ($arr, $searchVal, $leftIndex, $rightIndex) {

if ($rightIndex < $leftIndex) {
return 'ERROR';
}

$midIndex = round(($leftIndex + $rightIndex) / 2);
$midVal = $arr[$midIndex];
if ($searchVal < $midVal) {
BinarySearch($arr, $searchVal, $leftIndex, $midIndex - 1);
} else if ($searchVal > $midVal) {
BinarySearch($arr, $searchVal, $midIndex + 1, $rightIndex);
} else {
return $midIndex;
}

}

代码如上,var_dump出来的结果是空,但是如果把BinarySearch里面的两个return语句改成echo浏览器又能正常输出了,到底是哪出了问题?


回复讨论(解决方案)

function BinarySearch ($arr, $searchVal, $leftIndex, $rightIndex) {  if ($rightIndex < $leftIndex) {    return 'ERROR';  }  $midIndex = round(($leftIndex + $rightIndex) / 2);  $midVal = $arr[$midIndex];  if ($searchVal < $midVal) {    return BinarySearch($arr, $searchVal, $leftIndex, $midIndex - 1); //这里需要返回  } else if ($searchVal > $midVal) {    return BinarySearch($arr, $searchVal, $midIndex + 1, $rightIndex); //这里也需要返回  } else {    return $midIndex;  }}

人气教程排行