For vs Foreach in PHP: When to Use Each Loop for Best Performance
for is a C-style counter loop; foreach is a PHP-native iterator that walks arrays or objects without manual index handling.
Devs reach for for out of muscle memory, then swap to foreach when the offset math gets ugly—same data, two mindsets, one subtle performance trap.
Key Differences
for gives absolute control over index and direction, ideal for sparse or numeric arrays. foreach copies or references values, shielding you from off-by-one errors at the cost of extra memory when the array is huge.
Which One Should You Choose?
Pick for when you need reverse loops or manual slicing. Pick foreach for readability and associative keys. If the array is >10k items and you’re tight on RAM, benchmark both—PHP 8+ makes foreach nearly as fast.
Examples and Daily Life
Looping an API result? foreach ($users as $user) keeps code short. Writing a pagination engine? for ($i = $offset; $i < $limit; $i++) gives exact control without surprises.
Does foreach create a copy of the array?
By default yes, but foreach ($arr as &$v) uses a reference and avoids the copy.
Can I modify values inside a for loop?
Yes, since you’re working with direct indices: $arr[$i] *= 2; changes the original array in place.
Which is faster with huge arrays?
Modern PHP shows <1% difference; profile your case, but favor the loop that keeps your code readable first.