PHP Concatenation Pitfall: Initialize Before Using .=

📖 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!
        }
    }
}

Daryle De Silva

VP of Technology

11+ years building and scaling web applications. Writing about what I learn in the trenches.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *