Handy little function

Quite often I find myself wanting to run the same script by either cli or through a browser. But I don’t want to fill my echo statements with <br /> tags if I’m on cli because that’d just look ugly, but at the same time I don’t just want to use \n when outputting in the browser because everything would be on the same line.

This handy little function helps to do simple output that will be readable in the browser as well as the command line:

$_ = function($str) {
    if (PHP_SAPI == 'cli') {
        echo $str;
    } else {
        echo nl2br(str_replace("\t", str_repeat('&nbsp;', 6), $str))."\n";
        flush();
    }
};

Then when I want to echo something I just do:

$_("This is a test\n");
$_("\tTime:" . time() . "\n\n");

Simple but handy.

Did you like this? Share it:

Leave a Reply