PHP supports a wide variety of control structures, including if,
else, elseif, while, do-while,
for, foreach, switch, and others.
These are mostly similar to their Perl
counterparts. We saw the for loop above. Here is a more compact version
with a foreach statement that produces the same output. PHP creates a
copy of the array when foreach is used.
The for loop only works when the array keys are consecutive integers. This makes
the foreach statement the natural choice when the array keys are not
consecutive integers.
A third way to achieve the same thing is to use a while with list()
and each():
A while statement is better to use when you wish to modify the contents of the array
when iterating over it.
One control structure that is very useful in web programming is the include directive. It will
include and execute the argument to the include directive:
This is especially useful with web pages to include repetetive text such as HTML headers and
footers. It can make a large collection of HTML pages more maintainable allowing
centralization of these repetetive HTML structures. This also allows reuse of code by placing
object definitions and functions in a common file and then including them in scripts embedded
in individual HTML pages.
The require directive is similar with the difference that execution of the script will stop
if there is an error, for example, the included file not being found.
Function can exist independent of classes in PHP. The syntax is
Functions can also be defined within other functions and inside conditional statements, such as if statements. Function names are case-insensitive. Function arguments are normally passed by value, unless they are objects. If you want to pass an argument by reference place an & in front of the name.
Exceptions can be thrown and caught in PHP as in other languages to allow for better structuring or error handling code.
There are no user comments.
Please send ideas and opinions by email at alexamies@gmail.com.