PHP: return value from function and echo it directly?

94,808

Solution 1

You can use the special tags:

<?= get_info(); ?>

Or, of course, you can have your function echo the value:

function get_info() {
    $something = "test";
    echo $something;
}

Solution 2

Why return when you can echo if you need to?

function 
get_info() {
    $something = "test";
    echo $something;
}

Solution 3

Why not wrap it?

function echo_get_info() {
  echo get_info();
}

and

<div class="test"><?php echo_get_info(); ?></div>

Solution 4

Have the function echo the value out itself.

function get_info() {
    $something = "test";
    echo $something;
    return $something;
}

Solution 5

One visit to echo's Manual page would have yielded you the answer, which is indeed what the previous answers mention: the shortcut syntax.

Be very careful though, if short_open_tag is disabled in php.ini, shortcutting echo's won't work, and your code will be output in the HTML. (e.g. when you move your code to a different server which has a different configuration).

For the reduced portability of your code I'd advise against using it.

Share:
94,808
matt
Author by

matt

Updated on August 22, 2020

Comments

  • matt
    matt almost 4 years

    this might be a stupid question but …

    php

    function get_info() {
        $something = "test";
        return $something;
    }
    

    html

    <div class="test"><?php echo get_info(); ?></div>
    

    Is there a way to make the function automatically "echo" or "print" the returned statement? Like I wanna do this … 

    <div class="test"><?php get_info(); ?></div>
    

    … without the "echo" in it?

    Any ideas on that? Thank you in advance!

  • Jay K
    Jay K over 9 years
    For the record, as of php 5.4, "<?= is now always available, regardless of the short_open_tag php.ini option." See us1.php.net/manual/en/migration54.new-features.php
  • Sébastien REMY
    Sébastien REMY over 4 years
    May be he don't want to echo each time he use this function.
  • Asef Hossini
    Asef Hossini almost 3 years
    Maybe want to echo the returned value in some other function.