Bendegúz Csirmaz

PHP quiz #2 - echo

When people get into PHP development, the first thing they usually learn is the echo statement. Despite its elementary nature, I've found its handling of multiple arguments to be quite tricky.


What will this code output?


function a() {
  echo 'a';
  return 'a';

echo 'b', a(), "c\n";
  • A
  • B
  • C
  • D


Show the answer


If you're like me, you've probably guessed "abac", and under any other circumstances you would have been right.

When calling a function, every argument is evaluated before entering the function body.

Parameters vs Arguments

The catch is, echo is not a function. It's a language construct. It has special meaning for the interpreter, and as such, it works a little differently.

Instead of evaluating all the arguments eagerly, it evaluates them one by one.

Variable declarations

To understand the rationale behind echo's strange behaviour, consider variable declarations.

PHP allows declaring multiple variables in a single statement. The two code snippets below have the exact same effect:


class A {
  public $a = 'a', $b;

function b() {
  global $c, $d;
  static $e = 'e', $f;

class A {
  public $a = 'a';
  public $b;

function b() {
  global $c;
  global $d;
  static $e = 'e';
  static $f;

Although echo doesn't have much in common with variable declarations conceptually, it handles multiple arguments in a very similar way:

echo 'b', a(), "c\n";
echo 'b';
echo a();
echo "c\n";

That is, passing multiple arguments to echo is essentially the same as writing separate, consecutive echo statements.

This post is part of a series based on a presentation I gave on March 20, 2019.