Programming is, and will probably always be an interest of mine. I know when I first started out, I had questions, many, many questions.

One question that used to boggle my mind is why have so many different control structures that do the same thing. In essences for, foreach and while can be used to do the same exact thing. They loop through things. Each control structures though, can perform faster depending on what logic you are trying to do.

FOR

Reference Material: http://php.net/manual/en/control-structures.for.php

It is best used for integer based loops. For example:

$conn = mysql_connect("localhost", "mysql_user", "mysql_password");
mysql_select_db("mydbname");

$sql = "SELECT userid, fullname, userstatus FROM sometable WHERE userstatus = 1";

$result = mysql_query($sql);

while ($row = mysql_fetch_assoc($result)) {
    echo $row["userid"];
    echo $row["fullname"];
    echo $row["userstatus"];
}

Output would be dependent on what is in “sometable”. But you get the point.

While you could use each loop a different way, using these ways should use less resources when dealing with a large amount of data. It is also good code to use the control structures the way they were intended to be used.

Please note that you will want to not write code exactly as above due to not showing error handling in these examples, especially the WHILE example.

More reference material to look at:
All Control Structures: http://php.net/manual/en/language.control-structures.php
do-while (same a while except will execute first before evaluating): http://php.net/manual/en/control-structures.do.while.php

I hope to bring out more examples soon with coding in PHP, and maybe even have a whole section of tutorials. Until then, php.net is the best resource on learning everything about php.

~Joshua