Fixing old PHP code
I wrote a control panel in 2005 using PHP, without any framework. Who could have guessed it would still be in production now?
We’ve recently decided to put off replacing it for a few years, so I have to fix all the deprecation warnings, which are almost all due to:
while(list($k, $v) = each($array)) {
At some point, early in my PHP coding life, someone told me foreach($array as $k => $v) {
was bad. I don’t even remember why. But it stuck, so my code is
littered with the while/list/each approach. If I ever wrote malware in PHP you
could definitely fingerprint me with this one.
I’m working on some sed magic to fix them, starting with:
find . -name '*.php' -exec sed -E -i 's#while\(list\((\$[a-z_]*), ?(\$[a-z_]*)\) = each\((\$[a-z_>-]+)\)\) \{#foreach(\3 as \1 => \2) {#g' '{}' \;
But… it misses this variation:
while(list(, $v) = each($array)) {
So I also ran:
find . -name '*.php' -exec sed -E -i 's#while\(list\(,(\$[a-z_]*)\) = each\((\$[a-z_>-]+)\)\) \{#foreach(\2 as \1) {#g' '{}' \;
I ended up with 10 replacments I had to do by hand (while(list($k) = each($array))
and a few others with unusual spacing).