PHP Compatibility Code
PHPCompatibility.FunctionUse.RemovedFunctions.eachDeprecated
Recommendation
Replace all usages with this Compatibility_Php56::each()
method:
final class Compatibility_Php56
{
public static function each(array &$array)
{
if (current($array) === false) {
return false;
}
$key = key($array);
$value = current($array);
next($array);
return [
1 => $value,
'value' => $value,
0 => $key,
'key' => $key,
];
}
}
Before
list($key, $value) = each($array);
After
list($key, $value) = Compatibility_Php56::each($array);
Explanation
Compatibility_Php56::each()
behaves like its deprecated counterpart, each()
, which even preserves the ability to access the result's elements using both numeric and string keys (1
, value
, 0
and key
).
The reason why we can't just use foreach
is because that would not work in situations where we need to both get the values and advance the array's pointer in one expression. Example:
for ($i = 0; $i < $argLen; $i++) {
if ($i + 1 < $argLen) {
//...
break;
}
else if (list(, $optArg) = each($args)) {
}
else {
throw new Exception('');
}
}
In this situation, if we don't advance the pointer, we'd break the loop's logic. We can't advance the pointer inside the else if
, because the pointer has to advance regardless of whether the expression evaluates to true. Replacing it with Compatibility_Php56::each($args)
avoids lengthy case-by-case analysis and having to write unit tests for potentially untestable code.
Autoloading
Follow the guide PSR-0 Autoloading to load the Compatibility_Php56
into the legacy project.
Migration Services
Increase security and cut risk by simplifying PHP application upgrades and migrations.
Get Long-Term Support With ZendPHP
Stay secure and compliant while migrating on your schedule with Zend PHP LTS.