user3371049 user3371049 - 5 months ago 19
SQL Question

foreach function on $GLOBALS generates a fatal error

This function works on one field at a time:

foreach ($GLOBALS as $key => $value) {
if ($key === "special1") {
{$value = preg_replace('/src/','data-machin', $value);
}}}


This one - with no condition (so it tries to proccess 360 fields) does not:

foreach ($GLOBALS as $key => $value)
{$value = preg_replace('/src/','data-machin', $value);
}


and generates this Fatal error: Cannot increment/decrement overloaded objects nor string offsets in /home/xxx/public_html/lib/mysqldb.php on line 145.

How could I make it work?

(Big picture: I am trying to implement a script to delay the loading of photos).

Answer

preg_replace only makes sense for string values.

Thus, you may use the is_string function to check values when iterating:

foreach ($GLOBALS as $key => $value) {
    if (is_string($value)) {
        $value = preg_replace('/src/','data-machin', $value); 
    }
}

Also please note that this piece of code produces no side effects — i.e. the $GLOBALS array is not modified. You may consider using references instead:

foreach ($GLOBALS as $key => &$value) {
    ...
}
unset($value);