logo
podcast Podcast
get help Get Unstuck

One time echo versus print made an actual difference

Unlike tabs versus spaces

Joel Clermont
Joel Clermont
2024-08-02

Decades ago, it was common to use echo in PHP applications. In fact, we used it so much, we had a special short PHP tag <​?= to make it easier to type.

Today, though, it's pretty rare to see echo in a modern Laravel application.

One place it does get used is when streaming a download as your response.

For example, streaming a CSV file might look like this:

return response()->streamDownload(
    function () use ($csv) {
        echo $csv->toString();
    }, 
    $fileName, 
    [
        'Content-Type' => 'text/csv',
        'Content-Disposition' => sprintf('attachment; filename="%s"', $fileName),
    ]
);

With that setup out of the way, now to the question of the article: when might you need to use print instead of echo?

What if you want to refactor that anonymous function to an arrow function? In this example, echo will throw a parse error.

Parse error: syntax error, unexpected token "echo"

Why? Because the arrow function body must be a single expression that returns a value. echo has a void return type and never returns a value.

On the other hand, print always produces the return value 1, so you can use it.

This code works (and looks nicer, if you ask me):

return response()->streamDownload(fn() => print $csv->toString(), $fileName, [
    'Content-Type' => 'text/csv',
    'Content-Disposition' => sprintf('attachment; filename="%s"', $fileName),
]);

There's your dose of useful PHP trivia for the day.

Here to help,

Joel

P.S. I love figuring tricky things out. Are you stuck on something?

Toss a coin in the jar if you found this helpful.
Want a tip like this in your inbox every weekday? Sign up below 👇🏼
email
No spam. Only real-world advice you can use.