Search code examples
phpalgorithmrecursionbinary-search

Function returns null if return is called within a conditional statement despite meeting the condition. Returns expected value outside of conditional


I am trying to write a simple script that performs a binary search on an array. If I try to call return inside one of the conditionals, the program successfully runs but it does not return anything.

When I call var_dump() on the function it returns null. Below I have put some comments to show that it does return a value outside of the conditional statements. It also echos the expected value within the conditional.

Can anyone tell me what might be going on? I am at wits end.

<?php

$find = 56;
$data = array();

for($i = 1; $i < 100; $i++){

    $j = ($i * 2);

    array_push($data, $j);

}


function bin_sort($data,$find){
    //return $find; THIS WORKS
    $split = floor(count($data) / 2);
    $mid = $data[$split];
    if($mid == $find){
        return $mid;
        //echo $mid; THIS WORKS. IT ECHOS THE CORRECT VALUE
        //return 'test'; DOES NOT WORK
    }elseif($find > $mid){
        $key = array_search($mid, $data);
        $data1 = array_slice($data,$key);
        bin_sort($data1, $find);

    }elseif($find < $mid){
        $key = array_search($mid, $data);
        $data1 = array_slice($data, 0, $key);
        bin_sort($data1, $find);

    }
}

echo bin_sort($data, $find);


?>

Solution

  • Your recursive calls inside bin_sort are missing return before them, so if any recursion at all happens, the top level just returns null.