Sinister Beard
Sinister Beard

Reputation: 3680

Why are print_r and return returning different values?

I have the following custom function in PHP / Wordpress.

function GetAncestors($post_id, $ancestors = array()) {

    $query = 'SELECT `wp_terms`.term_id, `wp_terms`.name, `wp_term_taxonomy`.parent FROM `wp_terms` LEFT JOIN `wp_term_taxonomy` ON `wp_terms`.term_id = `wp_term_taxonomy`.term_id WHERE `wp_terms`.term_id = '.$post_id;
    $term_data = RunQuery($query)[0];
    array_push($ancestors,$term_data);
    if($term_data[parent]!='11') GetAncestors($term_data[parent],$ancestors);

    else print_r($ancestors);
    //else return $ancestors;

}

If I print_r the array, it returns the expected result. If I return the value of the array and print_r it outside of the function (which is what I want to do), it returns a blank string.

Results from print_r:

Array ( [0] => Array ( [term_id] => 95 [name] => PDR (Appraisals) [parent] => 91 ) [1] => Array ( [term_id] => 91 [name] => Your career, learning and development [parent] => 14 ) [2] => Array ( [term_id] => 14 [name] => You At ... [parent] => 11 ) ) 

Why is this?

Upvotes: 0

Views: 63

Answers (2)

Flosculus
Flosculus

Reputation: 6956

Shouldn't it be like this:

// Changed ancestors to reference
// Changed constant 'parent' to string
function GetAncestors($post_id, &$ancestors = array()) {

    $query = 'SELECT `wp_terms`.term_id, `wp_terms`.name, `wp_term_taxonomy`.parent FROM `wp_terms` LEFT JOIN `wp_term_taxonomy` ON `wp_terms`.term_id = `wp_term_taxonomy`.term_id WHERE `wp_terms`.term_id = '.$post_id;
    $term_data = RunQuery($query)[0];
    array_push($ancestors,$term_data);
    if($term_data['parent']!='11') {
        GetAncestors($term_data['parent'],$ancestors);
    }
}

$ancestors = array();
GetAncestors($id, $ancestors);

print_r($ancestors);

Personally I'd write it like this for utility:

function GetAncestors($post_id, &$ancestors = null) {
    if (null === $ancestors) {
        $ancestors = array();
    }

    $query  = 'SELECT `wp_terms`.term_id, `wp_terms`.name, `wp_term_taxonomy`.parent FROM `wp_terms` LEFT JOIN `wp_term_taxonomy` ON `wp_terms`.term_id = `wp_term_taxonomy`.term_id WHERE `wp_terms`.term_id = '.$post_id;
    $result = RunQuery($query);

    if (count($result) > 0) {
        $count = 1;
        $term_data = $result[0];
        array_push($ancestors,$term_data);

        if($term_data['parent']!='11') {
            $count += GetAncestors($term_data['parent'],$ancestors);
        }

        return $count;
    }

    return 0;
}

if (GetAncestors($id, $ancestors) > 0) {
    print_r($ancestors);
}

Upvotes: 1

henrik
henrik

Reputation: 1618

Use the return flag:

print_r($ancestors, true);

From php doc: http://php.net/manual/en/function.print-r.php

If you would like to capture the output of print_r(), use the return parameter. When this parameter is set to TRUE, print_r() will return the information rather than print it.

Upvotes: 0

Related Questions