Now Playing

PHP Tips #1: 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";
}
?>

Related posts:

  1. PHP and stdClass

Tags: ,

Leave a Reply

About

A Web Developer by nature and by trade. Living in Dublin, Ireland and working at Web Reservations International. Enjoys working on Open Source, web server stacks, XHTML/CSS, JavaScript and playing with the latest trends in technology.