# Fix `Call to undefined function each()` on PHP 8

Yes. An agent replaces every each() call that PHP 8 removed with foreach or key() and current(), proves the result on PHP 8, and opens a pull request.

[Run this on Rush](https://cloud.getrush.ai/run/fix-each-function-removed/php/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

PHP deprecated `each()` in 7.2 and removed it in 8.0. Code that walked an array with `while (list($key, $value) = each($array))`, or took an array's first pair with a single `each($array)`, now stops with `Uncaught Error: Call to undefined function each()`. In namespaced code the message carries the namespace, which makes it harder to search for. In moserware/PHPSkills, a TrueSkill and Elo rating library, it reads `Call to undefined function Moserware\Skills\Elo\each()`. The calls are in `src/Elo/TwoPlayerEloCalculator.php` on lines 33 and 34: `$player1 = each($team1);` and the same for `$team2`, followed by reads of `$player1["key"]` and `$player1["value"]`.

The obvious first step, running the tests on PHP 8, does not work here, and the agent says why instead of skipping it. `composer.json` requires `phpunit/phpunit` `~4.0`, and the lockfile pins packages such as phpspec/prophecy and doctrine/instantiator whose PHP constraints stop below 8.0, so `composer install` refuses on PHP 8.2 before a single test runs. The agent reproduces the error another way: a short script that registers an autoloader for `src/` and calls `calculateNewRatings` on a `FideEloCalculator` with the 1200 against 1500 case from `tests/Elo/FideEloCalculatorTest.php`. It dies at line 33 with the message above.

The replacement depends on what each call was for. These two are not loops. Each reads the only entry of an array that was assigned one line earlier, so `key($team1)` and `current($team1)` give the same pair without moving anything. The agent picks those two functions over `array_key_first` because `composer.json` still declares `"php": ">=5.3.0"` and they exist in every version. For a `while` loop over `each()`, the replacement is `foreach ($array as $key => $value)`, unless the loop body adds to the array or code after the loop relies on where the internal pointer stopped; the agent flags those cases instead of converting them blindly. With the change in place the same script returns ratings of about 1221.23 and 1478.77, inside the 0.1 tolerance that `EloAssert` allows around the expected 1221.25 and 1478.75.

It then reports what else stands between this library and PHP 8, because `each()` is rarely the only removal an old codebase runs into. `php -l src/Player.php` fails with `Cannot use "parent" when current class scope has no parent`: line 64 returns `parent::__toString()` from a class that extends nothing, so every TrueSkill path that loads `Player` is still fatal. The test suite needs a newer PHPUnit before it can run at all, which means changing the `\PHPUnit_Framework_TestCase` base class in `tests/TestCase.php` and the four-argument `assertEquals` calls that pass a delta. The agent fixes what the task names and lists the rest with file and line as follow-up work.

## Start it with one API call

`POST https://api.phoenix.so/o/{org}/sessions`

```json
{
  "agent": "claude",
  "input": "This project fails on PHP 8 with `Call to undefined function each()` (in namespaced code the message includes the namespace before each). Fix it. Find every call to each(), including the while (list($k, $v) = each($arr)) form and calls followed by reads of the 'key', 'value', 0 or 1 offsets. For each call decide what it was for: a loop over the whole array, a loop that modifies the array or depends on the internal pointer afterwards, or a single read of the current or first pair. Convert plain loops to foreach, single reads to key() and current() (or array_key_first where composer.json's PHP constraint allows it), and report any loop whose behaviour depends on the internal pointer instead of converting it. Do not add a polyfill function named each. Reproduce the error on PHP 8 before the change. If the project's pinned test tooling cannot install on PHP 8, say exactly which constraint blocks it, do not upgrade the test framework in this pull request, and prove the fix with a small script that exercises the changed code using inputs and expected values taken from the existing tests. Run php -l on every source file under PHP 8 and list any other fatal errors or removed functions you find, with file and line, without fixing them. Open a pull request.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
```

1. **Get an API key.** In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
2. **Send the request.** POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
3. **Read what came back.** Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

## What comes back

A pull request whose diff is a few lines per call site. The description pairs each change with the reason for the form chosen, `foreach` or `key()` and `current()`, and shows the reproduction on PHP 8 before the change and the same script's output after it, next to the expected values it took from the existing tests.

When the test suite cannot run on PHP 8, the description states the blocking constraint by package name and does not pretend otherwise. It does not claim the suite passes. A reviewer who still has PHP 7 available can run the untouched suite there against the branch, since `key()` and `current()` behave the same on both versions, and the description suggests exactly that.

The last section is the list of other PHP 8 problems found by linting every file: each with its path, line and the interpreter's message. For PHPSkills that list has the `parent::__toString()` call in `src/Player.php` and the PHPUnit 4 dependency. It tells the team how far the codebase is from running on PHP 8, which is usually the question behind the bug report.

## Run it on every Linear issue labelled php8

A PHP 8 migration tends to live in a tracker as one issue per error message. Create an automation in the Project with a `linear` trigger on `linear.issue.labeled`, set its `labels` to the label your team uses, and save this prompt in it. When someone in your Rush org adds the label to an issue, a run starts with the issue placed after the prompt, so the stack trace pasted into the issue reaches the agent as context.

The trigger needs a Linear connection for the member the automation runs as, made in the console under Settings → Connections. Label changes made by an app integration never fire it, so a bot that labels issues in bulk starts nothing. The automation's max runs per hour caps how many issues are picked up at once, and an issue past the cap waits as a queued run.

## Why run it on Rush?

This job needs an interpreter the project does not run on yet. A developer's machine has the PHP version the application is deployed with, and switching it to 8 to chase one error disturbs everything else they are working on. The agent's sandbox is its own machine: it installs PHP 8 and Composer there, hits the real installation failure and the real fatal error, and none of that touches a shared environment. The commands and their output stay in the session's transcript.

It also produces something a quick local fix would not: the inventory. Linting every file under the new interpreter and writing down each fatal error takes minutes for an agent and tends to be skipped by a person fixing a single bug. Because runs are independent, you can start one per repository in a PHP 5 or 7 estate and read the lists side by side to see which codebases are one line away from PHP 8 and which need a project.

## Frequently asked questions

### What replaces each() in PHP 8?

For a loop, `foreach ($array as $key => $value)`. For a single read of the current pair, `key($array)` and `current($array)`, followed by `next($array)` if the old code relied on the pointer advancing. PHP 7.3 and later also have `array_key_first` when only the first key is wanted.

### Can I just define my own each() function?

It makes the error go away and keeps alive a pattern PHP removed on purpose, so the next upgrade tool or static analyser will flag the same lines again. Converting the calls is usually a smaller diff than a polyfill plus its tests. The request tells the agent not to add one.

### Why does the error mention my namespace?

Inside a namespace PHP first looks for the function there and then falls back to the global one. When neither exists, the message names the namespaced lookup, for example `Moserware\Skills\Elo\each()`. The cause is the same removed global function.

### Is foreach always equivalent to the while and each() loop?

Not always. `foreach` iterates over the array as it was when the loop began, while the old loop saw elements appended during iteration and left the internal pointer at the end. The agent checks each loop body for writes to the array and for later `current()` or `key()` calls, and reports those loops instead of converting them.

### Will the agent upgrade PHPUnit too?

Not in this pull request. A test framework upgrade changes base classes and assertion calls across the suite and deserves its own review. The agent names the constraint that blocks the old version on PHP 8 and lists the upgrade as follow-up work.

## More PHP jobs

- [Fix `Call to undefined function get_magic_quotes_gpc()` When a PHP App Lands on PHP 8](https://getrush.ai/run/fix-get-magic-quotes-gpc-removed/php/)
- [Fix Call to Undefined Function mysql_connect() on PHP 7 and PHP 8](https://getrush.ai/run/fix-mysql-connect-function-removed/php/)
- [Fix "Passing null to parameter of type string is deprecated" on PHP 8.1 and later](https://getrush.ai/run/fix-passing-null-to-parameter-deprecated/php/)

## More jobs like this: Fix a bug from an alert

- [Fix "'xml.etree.ElementTree.Element' object has no attribute 'getchildren'" in Python 3.9+](https://getrush.ai/run/fix-elementtree-getchildren-attribute-error/elementtree/)
- [Fix "TypeError: db.collection(...).ensureIndex is not a function" after a MongoDB driver upgrade](https://getrush.ai/run/fix-ensureindex-is-not-a-function/mongodb/)
- [Fix ERR_PNPM_OUTDATED_LOCKFILE When CI Runs pnpm install](https://getrush.ai/run/fix-err-pnpm-outdated-lockfile/pnpm/)

## Keep reading

- [How a Rush run works on your repository, from request to pull request](https://getrush.ai/cloud/)
- [Compare cloud agents, agent sandboxes and AI code review](https://getrush.ai/compare/)
- [Rush pricing: Free, Pro and Max](https://getrush.ai/pricing/)
