PHP Tips #1: foreach Published 06 Feb 2009

I love foreach loops for their simplicity and readability, but they're a bit quirky when it comes to PHP. Here's a couple of tips I've picked up.

The following are functionally the same:

<?php $arr = array("one", "two", "three"); reset($arr); while (list($key, $value) = each($arr)) {     echo "Key: $key; Value: $value
\n"; } foreach ($arr as $key => $value) {     echo "Key: $key; Value: $value
\n"; } ?>

Ever want to drive straight into a foreach without checking that the array has elements?

<?php $non_array = null; foreach ((array) $non_array as $key => $value) {     echo "Key: $key; Value: $value
\n"; } ?>


Design and content © Jonathan Cremin