I have a function that will perform a SELECT query from some db and return either:
false(in case of error)- an empty array
array(0) { } - an associative array
In order to test the return value of this function, is it good practice to do :
$someVar = $this->someFunction();
if ($someVar) {
// ok, this is an associative array of result
} else {
// $someVar = false OR $someVar is an empty array
}
Or do I have to do something like this instead :
$someVar = $this->someFunction();
if (is_array($someVar) && count($someVar) > 0) {
// ok, this is an associative array of result
} else {
// $someVar = false OR $someVar is an empty array
}
The first test seems to do what I want, but maybe I’m missing something that might go wrong after.
So, is it good practice test arrays like I did in my first example?
Neither.
Returning
falseto indicate error is fine at a very low level, but there should a layer between your low-level queries and your application code which inspects the return value and throws an exception onfalse. The top-level controller which invokes your code should be handling those exceptions (which aren’t caught earlier) and displaying a user-friendly error page in production, or dumping debugging information in development, while logging the error.There is absolutely no way you should be doing a three-way
if/elseif/elsebranch in your application to inspect the return values of every single database query. This is an incredibly dated way of checking for errors.Throw exceptions, and you can use your first form (
if ($someVar)) or, better yet: