Search code examples
phpfunctionvariable-assignmentoutput-buffering

How to assign the echo statement from a function call to a variable?


I am trying to get the echo of a function and add the value into a variable.

So this is what I've done.

function myfunction() {
   echo 'myvar';
}

Then I want to get it into a variable like this:

$myVariable = myfunction();

I thought this would work but I isn't working.

Is this not the way to do this? If not, how do I do this?


Solution

  • You can call the function, while you have output buffering turned on and then you can capture the output. E.g.

    <?php
    
        ob_start();
        myfunction();
        $variable = ob_get_contents();
        ob_end_clean();
    
        echo $variable;
    
    ?>
    

    output:

    myvar
    

    Or you simply change the echo statement into a return statement.


    Your current version doesn't work, because you don't return the value from your function. And since you omitted the return statement the value NULL gets returned and assign to your variable. You can see this by doingthis:

    $variable = myfunction();
    var_dump($variable);
    

    output:

    NULL