13.09.2016 Views

PHP and MySQL Web Development 4th Ed-tqw-_darksiderg

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

156 Chapter 5 Reusing Code <strong>and</strong> Writing Functions<br />

Here, the function returns the larger of the two values passed in. It returns an obviously<br />

different value in the case of an error. If one of the numbers is missing, it returns<br />

false. (The only caveat with this approach is that programmers calling the function must<br />

test the return type with === to make sure that false is not confused with 0.)<br />

For comparison, the built-in function max() returns nothing if both variables are not<br />

set <strong>and</strong>, if only one was set, returns that one.<br />

The code<br />

$a = 1; $b = 2.5; $c = 1.9;<br />

echo larger($a, $b).’’;<br />

echo larger($c, $a).’’;<br />

echo larger($d, $a).’’;<br />

produces this output because $d does not exist <strong>and</strong> false is not visible:<br />

2.5<br />

1.9<br />

Functions that perform some task but do not need to return a value often return true<br />

or false to indicate whether they succeeded or failed.The boolean values true <strong>and</strong><br />

false can be represented with integer values 1 <strong>and</strong> 0, respectively, although they are of<br />

different types.<br />

Implementing Recursion<br />

Recursive functions are supported in <strong>PHP</strong>. A recursive function is one that calls itself.These<br />

functions are particularly useful for navigating dynamic data structures such as linked lists<br />

<strong>and</strong> trees.<br />

Few web-based applications, however, require a data structure of this complexity, so<br />

you have minimal use for recursion. It is possible to use recursion instead of iteration in<br />

many cases because both of these processes allow you to do something repetitively.<br />

However, recursive functions are slower <strong>and</strong> use more memory than iteration, so you<br />

should use iteration wherever possible.<br />

In the interest of completeness, let’s look at the brief example shown in Listing 5.5.<br />

Listing 5.5<br />

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!