Store function return value into variable

I am using a WordPress plugin for custom fields.

the_field('something')

is, I pressume, just echoing the return value.

Read More

Is it not possible to store that return value into a variable?

because $a = the_field('something'); is also echoing.

What I really want to do is this

if(the_field('something')) { 
     // echo the_field('something')
}
else
    // do something

but either way, it just echoes that thing in the page

Related posts

Leave a Reply

2 comments

  1. As I said in my comment, If a function just echos something, then there is no return value. But there is still a way to capture the output.

    Consider this function

    function doStuff()
    {
      echo 'hello';
    }
    

    You can’t get a return value from that, but you can capture the contents by using the ob_functions:

    ob_start();
    doStuff();
    $output = ob_get_contents(); 
    ob_end_clean();
    

    Now $output contains the output of that function, rather than it having been printed.

  2. WordPress I do not like. It seems that they have two functions (or more) for retrieving about anything. One echos it the_title() and the other returns it get_title(). For this plugin this should work:

    if($field = get_field('something')) { 
         echo $field;
    }
    else
        // do something
    }
    

    If you run across something that echos and doesn’t return a value and no corresponding function that does return something, then:

    ob_start();
    the_something();
    $output = ob_get_clean();
    // use $output