What does $wpdb->get_var return?

Sometimes the developer codex can be a little bit vague on what is returned in which case, and $wpdb->get_var was such a case for me recently. I needed to know what get_var would return on an empty result and the developer resource was a little unclear on that. So I took a quick look at the source code:

Source File: wp-includes/wp-db.php:

public function get_var( $query = null, $x = 0, $y = 0 ) {
    $this->func_call = "\$db->get_var(\"$query\", $x, $y)";
 
    if ( $this->check_current_query && $this->check_safe_collation( $query ) ) {
        $this->check_current_query = false;
    }
 
    if ( $query ) {
        $this->query( $query );
    }
 
    // Extract var out of cached results based x,y vals
    if ( !empty( $this->last_result[$y] ) ) {
        $values = array_values( get_object_vars( $this->last_result[$y] ) );
    }
 
    // If there is a value return it else return null
    return ( isset( $values[$x] ) && $values[$x] !== '' ) ? $values[$x] : null;
}

And if we look closely at the return line:

return ( isset( $values[$x] ) && $values[$x] !== '' ) ? $values[$x] : null;

We can see that:

I hope this can be of some help to you too.

Written by Jay - November 7, 2017
Tags:

Comments: