Skip to content
Advertisement

How to avoid echo when calling the function and want only the return value in PHP

my function where I am returning the value but when I am calling this function it also echo the other function.

function myFunction(){
       $output1 = anotherFunc();
       $output2 = " Hello World!";
       return $output2;
    }
    function anotherFunc(){
        echo "Hey this is paragraph";
    }
    
    $data = myFunction();
    print_r($data);

Advertisement

Answer

<?php
function myFunction(){
    ob_start();
    $output1 = anotherFunc();
    ob_end_clean();
    $output2 = " Hello World! $output1";

    return $output2;
}

function anotherFunc(){
    echo "Hey this is paragraph";
    return 5;
}
echo myFunction();

ob_start – This function will turn output buffering on. While output buffering is active no output is sent from the script (other than headers), instead the output is stored in an internal buffer.

ob_end_clean – This function discards the contents of the topmost output buffer and turns off this output buffering. If you want to further process the buffer’s contents you have to call ob_get_contents() before ob_end_clean() as the buffer contents are discarded when ob_end_clean() is called.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement