Jonathan Cremin


PHP Tips: foreach

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";
}
?>

I'm an engineering manager living in Dublin and working at Udemy. I've built stuff for Mac, iOS, and the web, like Hostr and Combine.fm. Want to get in touch? Email jonathan@crem.in or toot @kudos.

Recent Posts

View More