syntax error, unexpected identifier “%s”, expecting variable

Description

A foreach() structure requires a variable after the as keyword: in fact, it may be a variable, a property, a static property, an array index or the list() expression.

The same error also appears when the intersectional type syntax is used: While A& is valid PHP 8.0, it should be followed by a variable (a parameter), and it finds another type.

Example

<?php

foreach($a as b) {}

function foo(A&B $arg) {}

?>

Literal Examples

  • syntax error, unexpected identifier “B”, expecting variable

  • syntax error, unexpected identifier “b”, expecting variable

  • syntax error, unexpected identifier “Countable”, expecting variable

Solutions

  • Add the missing $ sign, to make the identifier an array.

  • Upgrade to PHP 8.2, with intersectional types.

  • Remove the intersectional types.