Nathan Hoad

PHP: For vs Foreach

In PHP there are two kinds of for loops: for and foreach. Something that has bothered me for a while is that whenever I wanted to iterate over an array while modifying the array items I had to use the ugly form of the for loop. This meant that I was introducing another variable to the mix just for the sake of accessing array items by index.

I discovered recently though, that you don't have to do it this way. All you have to do is get the reference to the array item:

$array = array('  test   ', '  items', '  with spaces ');

// this won't do anything
foreach ($array as $value) {
    $value = trim($value);

// note the '&' for reference
foreach ($array as &$value) {
    $value = trim($value);

// array items will now be trimmed
// array = ['test', 'items', 'with spaces']

As obvious as it seems now, I am amazed at how many people didn't know that it could be done and still use the messy form of for.

If I just made your day a little better then thank me with a coffee: