Code snippet 4 – echo and return

Posted February 9th, 2011 in Snippets and tagged by Metod

This one is in PHP. I stumbled upon a case, where I wanted to echo something and then return, so that execution of the script would stop. One way to do this was:

echo $sth;

But this was a 2-liner. I wanted to do this in a nice 1-line way. So one option to do this could be:


Which still feels wrong because in my opinion this is something in the line of the abuse of the exit construct. Besides, since PHP 4.2.0, exit construct does not print out the contents if the contents is actually an integer. So I found a solution to my problem:

return print $sth;

This line does exactly what I wanted. Outputs the contents (even if it is an integer) and breaks current script’s execution.