📖 1 minute read
PHP’s concatenation assignment operator (.=) will throw an ‘Undefined variable’ error if you use it on an uninitialized variable. Always initialize string variables before using .= in loops. This is especially common when conditionally building strings within nested loops where the variable might not exist when the condition first matches.
// ❌ WRONG: Undefined variable error
foreach ($records as $record) {
if ($record->type === 'important') {
foreach ($record->items as $item) {
$summary .= $item->text; // Error!
}
}
}
// ✅ CORRECT: Initialize first
$summary = ''; // Initialize empty string
foreach ($records as $record) {
if ($record->type === 'important') {
foreach ($record->items as $item) {
$summary .= $item->text; // Works!
}
}
}
Leave a Reply