Control structures give you the ability to do more sophisticated tasks with your scripts. Say for example you have an Excel spreadsheet with a list of addresses in CSV format, and you wanted to enter the information into a database. You could do it manually (quite a laborious, inefficient, and expensive task), or you could have PHP do it for you. How can you get PHP to loop through all the information? You can use one of the following control structures:

  • foreach
  • for
  • while

Say you wanted to skip addresses that aren't located in the United States. How can you get PHP to differentiate between the data? Using conditionals of course! The following terms represent some conditional statements in PHP:

  • if
  • else
  • elseif
  • case
  • switch

With conditionals, you need to use operators to test your conditions. Here are some examples:

  • == the two items are equal
  • != the two items are not equal

As well as:

  • && and
  • || or

A conditional mostly tests for truth. For example, the following code is asking whether what is between the parentheses is true:

<?phpif(5==2) { // then...}?>

In this case the condition is not true, so PHP will not execute what is between the curly brackets. Along these lines, you can use functions that return a boolean value of true of false. For example, the function:


returns a true/false value depending on whether a variable is set.

PHP Tasks:

  1. Please write some code using the above concepts to loop 10 times and pring "Hello world!" to a browser window.
  2. Once you have successfully completed task 1, add an if statement within the loop to skip loop number 7.
  3. Post your completed and working code to this page.

PHP Resources: