Handy little function

Last modified date

Comments: 0

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:

[code lang=”php”]
$_ = function($str) {
if (PHP_SAPI == ‘cli’) {
echo $str;
} else {
echo nl2br(str_replace("\t", str_repeat(‘&nbsp;’, 6), $str))."\n";
flush();
}
};
[/code]

Then when I want to echo something I just do:

[code lang=”php”]
$_("This is a test\n");
$_("\tTime:" . time() . "\n\n");
[/code]

Simple but handy.

Share

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.