Home >Backend Development >PHP Tutorial >PHP接收不到函数返回值

PHP接收不到函数返回值

WBOY
WBOYOriginal
2016-06-23 13:02:421646browse

for ($i = 0; $i  $arr[$i] = $i;
}

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


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

if ($rightIndex  return 'ERROR';
}

$midIndex = round(($leftIndex + $rightIndex) / 2);
$midVal = $arr[$midIndex];
if ($searchVal  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;  }}

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn