Approaches to Web Development for Bioinformatics

Previous  Contents  Next
References

Control Structures

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.


PHP

<?php
$geneList = array("HD" => 146, "SCN3A" => 472);
foreach ($geneList as $gene => $startPos) {
echo "$gene $startPos <br>";
}
?>

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():


PHP

<?php
$geneList = array("HD" => 146, "SCN3A" => 472);
while (list($gene,$startPos) = each($geneList)) {
echo "$gene $startPos <br>";
}
?>

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:

PHP

<?php
include "footer.html";
?>

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

PHP

<?php
function my_function($arg_1, $arg_2, /* ... */) {
return "My value";
}
?>

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.


Previous  Contents  Next
References

Contributed Comments and NotesAdd a comment.

There are no user comments.

Google

Please send ideas and opinions by email at alexamies@gmail.com.

© 2006-2007 Alex Amies