In php, should I return false, null, or an empty array in a method that would usually return an array?

后端 未结 8 606
面向向阳花
面向向阳花 2021-02-01 18:22

I\'ve found several responses to this, but none pertaining to PHP (which is an extremely weak typed language):

With regards to PHP, is it appropriate to return

8条回答
  •  庸人自扰
    2021-02-01 19:19

    Whichever you prefer, though I suggest an empty array for the for a good reason. You don't have to check the type first!

     $value) {
        echo $key . ' => ' . $value . PHP_EOL;
    }
    ?>
    

    In any other case, if you'd return false or null, you'd get an error at the foreach loop.

    It's a minuscule difference, though in my opinion a big one. I don't want to check what type of value I got, I want to assume it's an array. If there are no results, then it's an empty array.

    Anyway, as far as I'm concerned there are no "defaults" for returning empty values. Native PHP functions keep amazing me with the very different values it returns. Sometimes false, sometimes null, sometimes an empty object.

提交回复
热议问题