Array_pop + WordPress 3.7.1 “get_results” = error?

This is very odd. I just upgraded to WordPress 3.7.1, and I suddenly began getting the error

PHP Warning:  array_pop() expects parameter 1 to be array, null given in (...)

Here is the relevant piece of code:

Read More
$User = array_pop($RM->DB->get_results($RM->DB->prepare(
    'SELECT 
        `user_id` AS `ID`,
        `api_key` AS `key`
    FROM
        `rm_users` 
    WHERE
        user_id = %d'
    , $user_value)));

Here I’m using WordPress’s $wpdb object to query custom tables. The weird thing is if I change it to this:

$Users = $RM->DB->get_results($RM->DB->prepare(
    'SELECT 
        `user_id` AS `ID`,
        `api_key` AS `key`
    FROM
        `rm_users` 
    WHERE
        user_id = %d'
    , $user_value));
$User = array_pop($Users);

It works perfectly fine. If array_pop was receiving a null parameter, then it stands that $Users would be null and would cause the same error, but it is not null and it does not cause the error. It is the same way everywhere I use WordPress’s “get_results” method along with “array_pop”.

Is this a legitimate php bug, or is there some deep mechanic that I’m not aware of that would prevent array_pop from taking the output of a method directly?

Related posts

Leave a Reply

1 comment

  1. It does not appear to be a WP bug as far as I can tell, and I am unsure why it has only started since 3.7.1.

    I have run the following on a custom table using both methods you provide, on 3.7.1, and both return a single stdClass object as expected.

    // Get one out with pop
    print_r(array_pop($this->_wpdb->get_results($this->_wpdb->prepare(
        'SELECT
            CONCAT(user.firstname," ",user.surname) AS name,
            user.email,
            user.mobile,
            user.userType
        FROM user
        WHERE userId=%d
        LIMIT 1;',
        $userId))));
    
    // get one out with 2-step
    $users = $this->_wpdb->get_results($this->_wpdb->prepare(
        'SELECT
            CONCAT(user.firstname," ",user.surname) AS name,
            user.email,
            user.mobile,
            user.userType
        FROM user
        WHERE userId=%d
        LIMIT 1;',
        $userId));
    print_r(array_pop($users));
    

    Rather than using pop, use the get_row method:

    $User = $RM->DB->get_row($RM->DB->prepare(
        'SELECT 
            `user_id` AS `ID`,
            `api_key` AS `key`
        FROM
            `rm_users` 
        WHERE
            user_id = %s'
        , $user_value));
    

    Or if you would prefer the result as an associative array rather than an stdClass:

    $User = $RM->DB->get_row($RM->DB->prepare(
        'SELECT 
            `user_id` AS `ID`,
            `api_key` AS `key`
        FROM
            `rm_users` 
        WHERE
            user_id = %s'
        , $user_value), ARRAY_A);