Return Values

This post is over 8 years old and is probably out of date.

In #phpc we recently had a discussion about function return values; specifically from database queries.

I’m going to go on a (admittedly, rather sturdy looking) limb and say this applies to pretty much any function that returns from a data resource, not just a database .

My preference, is to return false only for error conditions, or when a function is supposed to only return one result (i.e. when selecting on a primary key) and fails to find any result.

However, it’s very rare that I care about whether I hit an error condition or just got no result when it comes to display — more to the point, my user doesn’t care.

There is a simply solution though, an empty array, also evaluates as false.

function getData()
    if (error()) {
        return false;
    } elseif (noData()) {
        return array();
    } else {
        return myData();

if (!$data = getData()) {
    foreach ($data as $row) {
         // Show data
} else {
    echo “No data found.”;

// or

$data = getData();

if ($data === false) {
    myLog(“Something Bad Happened!”);

if (!$data) {
   echo “No data found.”;
} else {
   // iterate

This gives the best of both worlds IMO — the ability to distinguish error conditions or not depending on if you need to in the given context.

– Davey


This might be the start of a series of thoughts on common API best practices