Tag Archives: iteration

PHP: How to Skip to the Next Iteration of a Loop CodeUnit 22 MAR 2010

By now, you’ll know that loops are essential to your livelihood as a programmer and as such you have lovingly nurtured your loops, nesting and expanding them, and in general just making them better little iterations with each passing moment in your life as a developer.

But what happens when you want a loop to skip over a particular section? What if you want to jump forward a couple of iterations and hit that all important third loop?

Well have no fear, in direct contrast the PHP’s handy little break directive, PHP also comes packaged with the neat continue functionality that allows you to literally skip ahead within any sort of loop structure.

Using the continue functionality turns out to be a pretty simple thing to do – after all, anywhere within any type of loop, you simply put continue; which if read will force the script into the next loop iteration, handy if you don’t want to process some or other variable because of its state this time around.

You can read up more about it as well as the other PHP control structures here.

Related Link: http://php.net/manual/en/control-structures.continue.php

Little PHP Tip: Array Iteration that Produces both Key and Value CodeUnit 04 NOV 2009

PHP tutorial logoA PHP quick tip on something I keep on forgetting. Now while the foreach functionality is great in iterating through an array and returning the array’s values, sometimes one wishes to also capture the key against which a particular value is stored and for this one should use the overloaded form of the foreach function (usually foreach ($arr as $value) ), namely:

foreach ($arr as $key => $value)

This returns two variables in the form of $key which is the actual key name used for the array item and $value which is the actual value stored for that particular array item.

Nifty.

If you want to test it out for yourself, simply plug an array of your own making into this little blob of code: 

foreach ($arr as $key => $value) {
    echo "Key: $key; Value: $value<br />n";
}