PHP For Loop

PHP For Loop
The ‘for’ loop in PHP allows you to repeat certain code in an easy and intuitive manner. We’re going to cover the basics of it and also dig deeper into its full potential.

Syntax

for (counter; condition; counter modifier)
{
	// Looping code goes here.
}

The counter is just a variable. The condition sets how many times the code should execute. The counter modifier determines how the counter is modified each loop.

For example, if we wanted to output the numbers 1-10 with a linebreak in between each of them we’d do this:

for ($i = 1; $i < 11; $i++)
{
	echo $i . "\n";
}

As you can see $i increments AFTER the code is executed. If it executed before the result would be 0-9.

Further Examples

Say we had an array, and we wanted to list off the values, separated by a new line. We would do the following:

$array = array("foo", "baz", "foobar", "foobaz");
$count = count($array);
for ($i = 0; $i < $count; $i++)
{
	echo $array[$i], "\n";
}

That would output:

foo
baz
foobar
foobaz

However, you might think you’re clever and try doing this:

$array = array("foo", "baz", "foobar", "foobaz");
for ($i = 0; $i < count($array); $i++)
{
	echo $array[$i], "\n";
}

Though you save a line by doing this and it has the same output, you’re also counting the number of entries in $array each time it loops, which is bad for performance. Though you most likely wouldn’t notice it in such a small array, you definitely would if it has 100+ entrie; this is why you should count an array before hand when using the PHP for loop.

You’re also not limited to just incrementing the variable either, for example you could do this:

for ($i = 0; $i < 51; $i = $i + 10)
{
	echo $i . "\n";
}

Which would output:

0
10
20
30
40
50

The for loop can be very useful, but make sure you use it correctly. If you’re unsure of the efficiency of your code you can always try the while loop.

foreach Loop

The foreach loop is very similar to the for loop but it’s meant specifically for arrays. We don’t recommend using it for large amounts of data since it tends to be slow.

Here’s the syntax:

foreach ($array as $value)
{
	// Execute code here
}

So if we wanted to down our above array example with foreach we’d just do this:

$array = array("foo", "baz", "foobar", "foobaz");
foreach ($array as $value)
{
	echo $value, "\n";
}

Again, we strongly recommend you do not use this where performance counts as it’s slower than the regular for loop.

We hope you beginners enjoyed this article!

This entry was posted in PHP. Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>