In php, empty arrays are falsey, not truthy

This entry is part 4 of 5 in the series php features

Maybe I should have known this. But I didn’t, to my detriment. Empty arrays are falsey. Like so.

$x = array(); /* An empty array */
is_array( $x ); /* True */
if ( ! $x ) { /* This code runs because $x is falsey */ }
if ( $x) { /* This code doesn't run because $x is falsey */ }
empty( $x ) /* True */
is_null ( $x ) /* False */
isset( $x ) /* True */

The rule that an empty array is falsey bit me when doing this sort of thing. Many SQL queries can return an empty result set, that is, a result set with zero rows in it. That’s a usally a legitimate result set, not

$resultset = $wpdb->get_results( $query );
if ( ! $resultset ) {   /* WRONG!! */
    /* The query threw an error. */
} else {
    /* There's an array of rows in $resultset */
}

To correctly deal with empty resultsets we need something like this.

$resultset = $wpdb->get_results( $query );
if ( ! is_array( $resultset ) ) {   /* or null === $resultset for the get_results method */
    /* The query threw an error. */
} else {
    /* There's an array of rows in $resultset */
}

php features

php’s microtime() function php composer, WordPress, and plugins

Leave a Comment