duanbei7005 2018-10-12 02:01
浏览 133
已采纳

如果在条件语句中调用return,则函数返回null,尽管满足条件。 返回条件之外的预期值

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);


?>
  • 写回答

2条回答 默认 最新

  • dongza5150 2018-10-12 02:04
    关注

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊