PHP cannot receive the function return value 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;
}
}
As shown in the code above, the result of var_dump is null, but if you change the two return statements in BinarySearch to the echo browser, the result can be output normally. what is the problem?
Reply to discussion (solution)
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); // return} else if ($ searchVal> $ midVal) {return BinarySearch ($ arr, $ searchVal, $ midIndex + 1, $ rightIndex); // You also need to return} else {return $ midIndex ;}}