UNIT - I What is PHP? Why use PHP? Embedding PHP with HTML, Enhancing further, PHP Language Basics: using variable in PHP, understanding Data types, operator and expressions. Making decisions: simple decision with if statements, switch, ternary operator, do..while loop, for statement, break, loop skip iteration, nested loop, Function: calling functions, working with variable functions, own functions references, recursive functions. What is PHP? PHP is a programming language for building dynamic, interactive Web sites. As a general rule, PHP programs run on a Web server, and serve Web pages to visitors on request. One of the key features of PHP is that you can embed PHP code within HTML Web pages, making it very easy for you to create dynamic content quickly. A dynamic Web page is a page whose contents can change automatically each time the page is viewed. Contrast this with a static Web page, such as a simple HTML file, which looks the same each time it ’ s displayed (at least until the page is next edited). Meanwhile, an interactive Web site is a site that responds to input from its visitors. PHP stands for PHP: Hypertext Preprocessor, which gives you a good idea of its core purpose: to process information and produce hypertext (HTML) as a result. (Developers love recursive acronyms, and PHP: Hypertext Preprocessor is a good example of one.) The process of running a PHP script on a Web server looks like this: 1. A visitor requests a Web page by clicking a link, or typing the page ’ s URL into the browser ’ s address bar. The visitor might also send data to the Web server at the same time, either using a form embedded in a Web page, or via AJAX (Asynchronous JavaScript And XML). 2. The Web server recognizes that the requested URL is a PHP script, and instructs the PHP engine to process and run the script. 3. The script runs, and when it ’ s finished it usually sends an HTML page to the Web browser, which the visitor then sees on their screen. The interesting stuff happens when a PHP script runs. Because PHP is so flexible, a PHP script can carry out any number of interesting tasks, such as: • Reading and processing the contents of a Web form sent by the visitor • Reading, writing, and creating files on the Web server • Working with data in a database stored on the Web server • Grabbing and processing data from other Web sites and feeds • Generating dynamic graphics, such as charts and manipulated photos Why PHP? • PHP runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.) • PHP is compatible with almost all servers used today (Apache, IIS, etc.) • PHP supports a wide range of databases • PHP is free. Download it from the official PHP resource: www.php.net • PHP is easy to learn and runs efficiently on the server side Embedding PHP within HTML PHP is that you can embed PHP code within HTML. In fact, each .php script that you write is essentially treated as an HTML page by default. If the page contains no < ?php ... ? > tags, the PHP engine just sends the contents of the file as - is to the browser. e.g <html> <head> <title>My first PHP Page</title> </head> <body> This is normal HTML code <?php // php code goes here ?> Back into normal HTML </body> </html PHP will only process things that are enclosed within one of its valid code blocks (such as <?php and ?>). Because of this, PHP effectively ignores everything that it was not specifically told to process and can be used to our advantage. For example, what will the output from the following be?. Using Variables in PHP Variables are a fundamental part of any programming language. A variable is simply a container that holds a certain value. Variables get their name because that certain value can change throughout the execution of the script. It ’ s this ability to contain changing values that make variables so useful. For example, consider the following simple PHP script: echo 2 + 2; As you might imagine, this code outputs the number 4 when it ’ s run. This is all well and good; however, if you wanted to print the value of, say, 5 + 6 instead, you ’ d have to write another PHP script, as follows: echo 5 + 6; This is where variables come into play. By using variables instead of numbers in your script, you make the script much more useful and flexible: echo $x + $y; You now have a general - purpose script. You can set the variables $x and $y to any two values you want, either at some other place in your code, or as a result of input from the user. Then, when you run the preceding line of code, the script outputs the sum of those two values. Re - run the script with different values for $x and $y , and you get a different result. Naming Variables A variable consists of two parts: the variable ’ s name and the variable ’ s value. Because you ’ ll be using variables in your code frequently, it ’ s best to give your variables names you can understand and remember. Like other programming languages, PHP has certain rules you must follow when naming your variables: Variable names begin with a dollar sign ( $ ) The first character after the dollar sign must be a letter or an underscore The remaining characters in the name may be letters, numbers, or underscores without a fixed limit Variable names are case - sensitive ( $Variable and $variable are two distinct variables), so it ’ s worth sticking to one variable naming method — for example, always using lowercase — to avoid mistakes. It ’ s also worth pointing out that variable names longer than 30 characters are somewhat impractical. Here are some examples of PHP variable names: $my_first_variable $anotherVariable $x $_123 CREATING VARIABLES Creating a variable in PHP is known as declaring it. Declaring a variable is as simple as using its name in your script: $my_first_variable; When PHP first sees a variable ’ s name in a script, it automatically creates the variable at that point. Many programming languages prevent you from using a variable without first explicitly declaring (creating) it. But PHP lets you use variables at any point just by naming them. This is not always the blessing you might think; if you happen to use a nonexistent variable name by mistake, no error message is generated, and you may end up with a hard - to - find bug. In most cases, though, it works just fine and is a helpful feature. When you declare a variable in PHP, it ’ s good practice to assign a value to it at the same time. This is known as initializing a variable. By doing this, anyone reading your code knows exactly what value the variable holds at the time it ’ s created. (If you don ’ t initialize a variable in PHP, it ’ s given the default value of null .) Here ’ s an example of declaring and initializing a variable: $my_first_variable = 3; This creates the variable called $my_first_variable , and uses the = operator to assign it a value of 3. (You look at = and other operators later in this chapter.) Looking back at the addition example earlier, the following script creates two variables, initializes them with the values 5 and 6 , then outputs their sum ( 11 ): $x = 5; $y = 6; echo $x + $y; UNDERSTANDING DATA TYPES All data stored in PHP variables fall into one of eight basic categories, known as data types . A variable ’ s data type determines what operations can be carried out on the variable ’ s data, as well as the amount of memory needed to hold the data. PHP supports four scalar data types. OPERATORS AND EXPRESSIONS So far you ’ ve learned what variables are, and how to set a variable to a particular value, as well as how to retrieve a variable ’ s value and type. However, life would be pretty dull if this was all you could do with variables. This is where operators come into play. Using an operator, you can manipulate the contents of one or more variables to produce a new value. For example, this code uses the addition operator ( + ) to add the values of $x and $y together to produce a new value: echo $x + $y; So an operator is a symbol that manipulates one or more values, usually producing a new value in the process. Meanwhile, an expression in PHP is anything that evaluates to a value; this can be any combination of values, variables, operators, and functions. In the preceding example, $x + $y is an expression. Here are some more examples of expressions: $x + $y + $z $x - $y $x 5 true gettype( $test_var ) The values and variables that are used with an operator are known as operands . Operator Types Operators in PHP can be grouped into ten types, as follows: Arithmetic Operators In PHP, the arithmetic operators (plus, minus, and so on) work much as you would expect, enabling you to write expressions as though they were simple equations. For example, $c = $a + $b adds $a and $b and assigns the result to $c . Here ’ s a full list of PHP ’ s arithmetic operators Assignment Operators You ’ ve already seen how the basic assignment operator ( = ) can be used to assign a value to a variable: $test_var = 8.23; It ’ s also worth noting that the preceding expression evaluates to the value of the assignment: 8.23. This is because the assignment operator, like most operators in PHP, produces a value as well as carrying out the assignment operation. This means that you can write code such as: $another_var = $test_var = 8.23; which means: “ Assign the value 8.23 to $test_var , then assign the result of that expression ( 8.23 ) to $another_var . ” So both $test_var and $another_var now contain the value 8.23 . The equals sign ( = ) can be combined with other operators to give you a combined assignment operator that makes it easier to write certain expressions. The combined assignment operators (such as +=, – =, and so on) simply give you a shorthand method for performing typical arithmetic operations, so that you don ’ t have to write out the variable name multiple times. For example, you can write: $first_number += $second_number; rather than: $first_number = $first_number + $second_number; This also works for other kinds of operators. For example, the concatenation operator (described later in this chapter) can be combined with the equals sign (as .= ), causing the value on the right side to be appended to the existing value on the left, like this: $a = “Start a sentence “; $b = “and finish it.”; $a .= $b; // $a now contains “ Start a sentence and finish it. ” The main arithmetic, string, and bitwise operators support combination in this fashion; find out more at http://www.php.net/manual/en/language.operators.assignment.php Bitwise Operators PHP ’ s bitwise operators let you work on the individual bits within integer variables. Consider the integer value 1234. For a 16 - bit integer, this value is stored as two bytes: 4 (the most significant byte) and 210 (the least significant). 4 * 256 + 210 = 1234. Here ’ s how those two bytes look as a string of bits: 00000100 11010010 A bit with a value of 1 is said to be set , whereas a bit with a value of 0 is unset (or not set). PHP ’ s bitwise operators let you manipulate these bits directly, as shown in the following table. Each example includes both decimal values and their binary equivalents, so you can see how the bits are altered: Comparison Operators As you might imagine from the name, comparison operators let you compare one operand with the other in various ways. If the comparison test is successful, the expression evaluates to true ; otherwise, it evaluates to false . You often use comparison operators with decision and looping statements such as if and while Incrementing /Decrementing Operators Oftentimes it ’ s useful to add or subtract the value 1 (one) over and over. This situation occurs so frequently — for example, when creating loops — that special operators are used to perform this task: the increment and decrement operators. They are written as two plus signs or two minus signs, respectively, preceding or following a variable name, like so: ++$x; // Adds one to $x and then returns the result $x++; // Returns $x and then adds one to it – - $x; // Subtracts one from $x and then returns the result $x – - ; // Returns $x and then subtracts one from it The location of the operators makes a difference. Placing the operator before the variable name causes the variable ’ s value to be incremented or decremented before the value is returned; placing the operator after the variable name returns the current value of the variable first, then adds or subtracts one from the variable. For example: $x = 5; echo ++$x; // Displays “6” (and $x now contains 6) $x = 5; echo $x++; // Displays “5” (and $x now contains 6) Interestingly, you can use the increment operator with characters as well. For example, you can “ add ” one to the character B and the returned value is C. However, you cannot subtract from (decrement) character values. Logical Operators PHP ’ s logical operators work on Boolean values. Before looking at how logical operators work, it ’ s worth taking a bit of time to explore Boolean values more thoroughly. As you ’ ve already seen, a Boolean value is either true or false . PHP automatically evaluates expressions as either true or false when needed, although as you ’ ve already seen, you can use settype() or casting to explicitly convert a value to a Boolean value if necessary. For example, the following expressions all evaluate to true : 1 1 == 1 3>2 “hello” != “goodbye” The following expressions all evaluate to false : 3<2 gettype( 3 ) == “array” “hello” == “goodbye” In addition, PHP considers the following values to be false : The literal value false The integer zero ( 0 ) The float zero ( 0.0 ) An empty string ( “ “ ) The string zero ( “0” ) An array with zero elements The special type null (including any unset variables) A SimpleXML object that is created from an empty XML tag (more on SimpleXML in Chapter 19 ) All other values are considered true in a Boolean context. Now that you know how Boolean values work you can start combining Boolean values with logical operators. PHP features six logical operators, and they all work in combination with true or false Boolean values to produce a result of either true or false : Here are some simple examples of logical operators in action: $x = 2; $y = 3; echo ( ($x > 1) & & ($x < 5) ) . “ < br / > ”; // Displays 1 (true) echo ( ($x == 2) or ($y == 0) ) . “ < br / > ”; // Displays 1 (true) echo ( ($x == 2) xor ($y == 3) ) . “ < br / > ”; // Displays “” (false) because both // expressions are true echo ( !($x == 5 ) ) . “ < br / > ”; // Displays 1 (true) because // $x does not equal 5 The main use of logical operators and Boolean logic is when making decisions and creating loops, which you explore in Chapter 4 . You ’ re probably wondering why the and and or operators can also be written as & & and || . The reason is that and and or have a different precedence to & & and || . Operator precedence is explained in a moment. String Operators There ’ s really only one string operator, and that ’ s the concatenation operator , . (dot). This operator simply takes two string values, and joins the right - hand string onto the left - hand one to make a longer string. For example: echo “Shaken, “ . “not stirred”; // Displays “ Shaken, not stirred ” You can also concatenate more than two strings at once. Furthermore, the values you concatenate don ’ t have to be strings; thanks to PHP ’ s automatic type conversion, non - string values, such as integers and floats, are converted to strings at the time they ’ re concatenated: $tempF = 451; // Displays “ Books catch fire at 232.777777778 degrees C. ” echo “Books catch fire at “ . ( (5/9) * ($tempF - 32) ) . “ degrees C.”; In fact, there is one other string operator — the combined assignment operator .= — which was mentioned earlier in the chapter. It ’ s useful when you want to join a new string onto the end of an existing string variable. For example, the following two lines of code both do the same thing — they change the string variable $x by adding the string variable $y to the end of it: $x = $x . $y; $x .= $y; MAKING DECISION PHP Conditional Statements Very often when you write code, you want to perform different actions for different decisions. You can use conditional statements in your code to do this. In PHP we have the following conditional statements: • if statement - executes some code only if a specified condition is true • if...else statement - executes some code if a condition is true and another code if the condition is false • if...elseif....else statement - selects one of several blocks of code to be executed • switch statement - selects one of many blocks of code to be executed PHP - The if Statement The if statement is used to execute some code only if a specified condition is true. Syntax if (condition) { code to be executed if condition is true; } The example below will output "Have a good day!" if the current time (HOUR) is less than 20: Example <?php $t=date("H"); if ($t<"20") { echo "Have a good day!"; } ?> PHP - The if...else Statement Use the if....else statement to execute some code if a condition is true and another code if the condition is false. Syntax if (condition) { code to be executed if condition is true; } else { code to be executed if condition is false; } The example below will output "Have a good day!" if the current time is less than 20, and "Have a good night!" otherwise: Example <?php $t=date("H"); if ($t<"20") { echo "Have a good day!"; } else { echo "Have a good night!"; } ?> PHP - The if...elseif....else Statement Use the if....elseif...else statement to select one of several blocks of code to be executed. Syntax if (condition) { code to be executed if condition is true; } elseif (condition) { code to be executed if condition is true; } else { code to be executed if condition is false; } The example below will output "Have a good morning!" if the current time is less than 10, and "Have a good day!" if the current time is less than 20. Otherwise it will output "Have a good night!": Example <?php $t=date("H"); if ($t<"10") { echo "Have a good morning!"; } elseif ($t<"20") { echo "Have a good day!"; } else { echo "Have a good night!"; } ?> The PHP switch Statement Use the switch statement to select one of many blocks of code to be executed. Syntax switch (n) { case label1: code to be executed if n=label1; break; case label2: code to be executed if n=label2; break; case label3: code to be executed if n=label3; break; ... default: code to be executed if n is different from all labels; } This is how it works: First we have a single expression n (most often a variable), that is evaluated once. The value of the expression is then compared with the values for each case in the structure. If there is a match, the block of code associated with that case is executed. Use break to prevent the code from running into the next case automatically. Thedefault statement is used if no match is found. Example <?php $favcolor="red"; switch ($favcolor) { case "red": echo "Your favorite color is red!"; break; case "blue": echo "Your favorite color is blue!"; break; case "green": echo "Your favorite color is green!"; break; default: echo "Your favorite color is neither red, blue, or green!"; } ?> PHP Loops Often when you write code, you want the same block of code to run over and over again in a row. Instead of adding several almost equal code-lines in a script, we can use loops to perform a task like this. In PHP, we have the following looping statements: • while - loops through a block of code as long as the specified condition is true • do...while - loops through a block of code once, and then repeats the loop as long as the specified condition is true • for - loops through a block of code a specified number of times • foreach - loops through a block of code for each element in an array The PHP while Loop The while loop executes a block of code as long as the specified condition is true. Syntax while (condition is true) { code to be executed; } The example below first sets a variable $x to 1 ($x=1;). Then, the while loop will continue to run as long as $x is less than, or equal to 5. $x will increase by 1 each time the loop runs ($x++;): Example <?php $x=1; while($x<=5) { echo "The number is: $x <br>"; $x++; } ?> The PHP do...while Loop The do...while loop will always execute the block of code once, it will then check the condition, and repeat the loop while the specified condition is true. Syntax do { code to be executed; } while (condition is true); The example below first sets a variable $x to 1 ($x=1;). Then, the do while loop will write some output, and then increment the variable $x with 1. Then the condition is checked (is $x less than, or equal to 5?), and the loop will continue to run as long as $x is less than, or equal to 5: Example <?php $x=1; do { echo "The number is: $x <br>"; $x++; } while ($x<=5); ?> Notice that in a do while loop the condition is tested AFTER executing the statements within the loop. This means that the do while loop would execute its statements at least once, even if the condition fails the first time. The example below sets the $x variable to 6, then it runs the loop, and then the condition is checked: Example <?php $x=6; do { echo "The number is: $x <br>"; $x++; } while ($x<=5); ?> The PHP for Loop The for loop is used when you know in advance how many times the script should run. Syntax for (init counter; test counter; increment counter) { code to be executed; } Parameters: • init counter: Initialize the loop counter value • test counter: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues. If it evaluates to FALSE, the loop ends. • increment counter: Increases the loop counter value The example below displays the numbers from 0 to 10: Example <?php for ($x=0; $x<=10; $x++) { echo "The number is: $x <br>"; } ?> he PHP foreach Loop The foreach loop works only on arrays, and is used to loop through each key/value pair in an array. Syntax foreach ($array as $value) { code to be executed; } For every loop iteration, the value of the current array element is assigned to $value and the array pointer is moved by one, until it reaches the last array element. The following example demonstrates a loop that will output the values of the given array ($colors): Example <?php $colors = array("red","green","blue","yellow"); foreach ($colors as $value) { echo "$value <br>"; } ?> FUNCTIONS If you ’ ve been following the book up to now, you ’ re already familiar with the concept of functions. You ’ ve used built - in functions such as gettype() for determining the type of a variable, and count() that returns the number of elements in an array. How to create your own functions to make your code easier to read and work with All about parameters and arguments — you use these to pass values into your functions — and how to return values from functions. (With these techniques, your functions can communicate with the code that calls them) Variable scope and how to use local, global, and static variables to your advantage How to create anonymous functions, which are useful when you need to create simple, disposable functions Calling Functions If you ’ ve worked through the previous chapters you ’ ve already called quite a few of PHP ’ s built - in functions. To call a function, you write the function name, followed by an opening and a closing parenthesis: functionName() If you need to pass arguments to the function, place them between the parentheses, separating each argument by commas: functionName( argument ) functionName( argument1, argument2 ) If a function returns a value, you can assign the value to a variable: $returnVal = functionName( argument ); You can also pass the return value directly to another function, such as print() : print( functionName( argument ) ); In general terms, the return value of a function call is an expression, which means you can use a function ’ s return value anywhere that you can use an expression. When you call a function from within your script, the PHP engine jumps to the start of that function and begins running the code inside it. When the function is finished, the engine jumps back to the point just after the code that called the function and carries on from there. Here ’ s a simple example that illustrates this point: < html > < head > < title > Square roots < /title > < link rel=”stylesheet” type=”text/css” href=”common.css” / > < /head > < body > < h1 > Square roots < /h1 > < ?php echo “The square root of 9 is: “ . sqrt( 9 ) . “. < br/ > ”; echo “All done! < br/ > ”; ?> < /body > This code produces the output shown in Figure 7 - 1 . Here ’ s how it works: After displaying the XHTML page header, the first echo() line is run, and the PHP engine evaluates the expression after the echo() statement. This includes a function call to PHP ’ s built in sqrt() function, which determines the square root of its argument (in this case, 9 ) The engine jumps to the code for the sqrt() function and runs it. The function does its job and exits, returning the value 3 The engine jumps back to the first echo() statement and, now that it knows the result of the call to sqrt() , evaluates the rest of the expression, producing the string: “ The square root of 9 is: 3. ” This string value is then displayed in the Web page using the echo() statement Finally, the engine moves to the next line of code, and displays the “ All done! ” message Working with Variable Functions When you include a function call in your code, most of the time you ’ ll know the name of the function you want to call. However, sometimes it ’ s useful to be able to store the name of a function in a string variable, and use that variable instead of the function name when calling a function. Here ’ s an example: $squareRoot = “sqrt”; echo “The square root of 9 is: “ . $squareRoot( 9 ) . “. < br/ > ”; echo “All done! < br/ > ”; As you can see, the first line of code stores the function name, “ sqrt ” , as a string in the $squareRoot variable. This variable is then used in place of the function name on the second line. This example is fairly trivial, but it shows how the concept works. Here ’ s a slightly more complex example: $trigFunctions = array( “sin”, “cos”, “tan” ); $degrees = 30; foreach ( $trigFunctions as $trigFunction ) { echo “$trigFunction($degrees) = “ . $trigFunction( deg2rad( $degrees ) ) . “ < br/ > ”; } This code creates an array of three built - in function names — “ sin ” , “ cos ”, and “ tan “ — and sets up a $degrees variable. It then loops through the array. For each element, it calls the function whose name is stored in the element, passing in the value of $degrees converted to radians (using PHP ’ s built - in deg2rad() function), and displays the result. Here ’ s the output from the code: sin(30) = 0.5 cos(30) = 0.866025403784 tan(30) = 0.57735026919 In the real world, variable function calling is often used to dynamically select a function to execute on the fly, depending on, for example, user input or other external factors. You can also use it to write code that calls user - created callback functions or event handler functions. Writing Your Own Functions So far you ’ ve learned that functions are useful beasts that let you encapsulate and reuse code, and you ’ ve explored how to call functions in PHP. Here ’ s where the fun really begins, as you get to create your own functions. Defining a function is really easy — just use the following syntax: function myFunc() { // (do stuff here) } In other words, you write the word function , followed by the name of the function you want to create, followed by parentheses. Next, put your function ’ s code between curly brackets ( {} ). Here ’ s a trivial example: function hello() { echo “Hello, world! < br/ > ”; } // Displays “Hello, world!” hello(); As you can see, this script defines a function, hello() , that simply displays the string “ Hello, world! ” After the function definition, the script calls the hello() function to display the output. Notice that the code within the hello() function is only run when the function is later called, not when the function itself is created. Simply creating a function does not run the code within the function; you have to explicitly call the function in order to run its code. Working with References You ’ ve already learned that you can pass information to a function in the form of arguments, as well as return information from a function to its calling code using the return statement. When you do either of these things, PHP actually passes copies of the information to and from the function; this is known as passing and returning by value . Most of the time this isn ’ t a problem, but sometimes you want your function to work on the original information, rather than on a copy. Consider the following example: function resetCounter( $c ) { $c = 0; } $counter = 0; $counter++; $counter++; $counter++; echo “$counter < br/ > ”; // Displays “3” resetCounter( $counter ); echo “$counter < br/ > ”; // Displays “3” This code defines a function, resetCounter() , that resets its argument to zero. A $counter variable is then initialized to zero and incremented three times. As you ’ d expect, the value of $counter at this point is 3 . resetCounter() is then called, passing in $counter , the variable to reset. However, as the second echo statement shows, $counter has not been reset by the function. This is because the parameter $c inside resetCounter() merely holds a copy of the information stored in $counter . So when the function sets $c to zero, it doesn ’ t affect the value of $counter at all. Fortunately, PHP provides a mechanism known as references that you can use to work around such issues. A reference is a bit like a shortcut or alias to a file on your hard drive. When you create a reference to a PHP variable, you now have two ways to read or change the variable ’ s contents — you can use the variable name, or you can use the reference. Here ’ s a simple example that creates a reference to a variable: $myVar = 123; $myRef = & $myVar; $myRef++; echo $myRef . “ < br/ > ”; // Displays “124” echo $myVar . “ < br/ > ”; // Displays “124” First a new variable, $myVar , is initialized with the value 123 . Next, a reference to $myVar is created, and the reference is stored in the variable $myRef . Note the ampersand ( & ) symbol after the equals sign; using this symbol creates the reference. The next line of code adds one to the value of $myRef . Because $myRef actually points to the same data as $myVar , both $myRef and $myVar now contain the value 124 , as shown by the two echo statements. Now that you know what references are, and how to create them, it ’ s time to look at how you can pass references into and out of your functions. Passing References to Your Own Functions By passing a reference to a variable as an argument to a function, rather than the variable itself, you pass the argument by reference , rather than by value. This means that the function can now alter the original value, rather than working on a copy. To get a function to accept an argument as a reference rather than a value, put an ampersand ( & ) before the parameter name within the function definition: function myFunc( & $aReference ){ // (do stuff with $aReference) } Now, whenever a variable is passed to myFunc() , PHP actually passes a reference to that variable, so that myFunc() can work directly with the original contents of the variable, rather than a copy. Now that you know this, you can fix the earlier counter example by using a reference: function resetCounter( & $c ) { $c = 0; } $counter = 0; $counter++; $counter++; $counter++; echo “$counter < br/ > ”; // Displays “3” resetCounter( $counter ); echo “$counter < br/ > ”; // Displays “0” The only change in the script is in the first line: function resetCounter( & $c ) { Adding the ampersand before the $c causes the $c parameter to be a reference to the passed argument ( $counter in this example). Now, when the function sets $c to zero, it ’ s actually setting the value of $counter to zero, as can be seen by the second echo statement. Many built - in PHP functions accept references in this way. For example, PHP ’ s sort() function, which you met in the previous chapter, changes the array you pass to it, sorting its elements in order. The array is passed in by reference rather than by value, so that the function can change the array itself, rather than a copy of it. Recursive Functions Recursion is another technique that you can use if you need to work on a set of values. Generally speaking, it ’ s usually easier to use iteration than recursion; however, in certain situations recursion makes more sense. Practically any loop can be converted to use recursion instead, and vice - versa. So what is recursion, and how does it relate to functions? Well, in simple terms, recursion occurs when a function calls itself. As you ’ d imagine, such a process would repeat indefinitely if not stopped, so the recursion needs to have some sort of end condition — much like a loop. This end condition is known as the base case , and the part of the function that calls itself is known as the recursive case . Here ’ s a quick overview of how a recursive function operates: The recursive function is called by the calling code If the base case, or end condition, is met, the function does any processing required, then exits Otherwise, the function does any processing required, then calls itself to continue the recursion Of course, you have to make sure that the base case is eventually reached, otherwise the function will keep calling itself indefinitely (causing an infinite loop). ADDITIONALS STRING FUNCTIONS the Php language comes with a full-featured library of built-in functions that let you do everything from reversing and splitting strings to calculating logarithmic values PHP has over 75 built-in string manipulation functions, supporting operations ranging from string repetition and reversal to comparison and search-and-replace. Table 3-3 lists some of these functions. Checking for Empty Strings The empty() function returns true if a string variable is “empty.” Empty string variables are those with the values '', 0, '0', or NULL. The empty() function also returns true when used with a non-existent variable. Here are some examples: <?php // test if string is empty // output: true $str = ''; echo (boolean) empty($str); // output: true $str = null; echo (boolean) empty($str); // output: true $str = '0'; echo (boolean) empty($str); // output: true unset($str); echo (boolean)empty($str); ?> Checking for Empty Strings The empty() function returns true if a string variable is “empty.” Empty string variables are those with the values '', 0, '0', or NULL. The empty() function also returns true when used with a non-existent variable. Here are some examples: <?php // test if string is empty // output: true $str = ''; echo (boolean) empty($str); // output: true $str = null; echo (boolean) empty($str); // output: true $str = '0'; echo (boolean) empty($str); // output: true unset($str); echo (boolean)empty($str); ?> strlen() function The strlen() function returns the length of a string, in characters. The example below returns the length of the string "Hello world!": <html> <body> <?php echo strlen("Hello world!"); ?> </body> </html> The PHP strpos() function The strpos() function is used to search for a specified character or text within a string. If a match is found, it will return the character position of the first match. If no match is found, it will return FALSE. The example below searches for the text "world" in the string "Hello world!": <html> <body> <?php echo strpos("Hello world!","world"); ?> </body> </html> str_replace() Function Definition and Usage The str_replace() function replaces some characters with some other characters in a string. e.g Replace the characters "world" in the string "Hello world!" with "Peter": <?php echo str_replace("world","Peter","Hello world!"); ?> Reversing and Repeating Strings The strlen() function returns the number of characters in a string. Here’s an example of it in action: <?php // calculate length of string // output: 17 $str = 'Welcome to Xanadu'; echo strlen($str); ?> Reversing a string is as simple as calling the strrev() function, as in the next listing: <?php // reverse string // output: 'pets llams enO' $str = 'One small step'; echo strrev($str); ? Working with Substrings PHP also allows you to slice a string into smaller parts with the substr() function, which accepts three arguments: the original string, the position (offset) at which to start slicing, and the number of characters to return from the starting position. The following listing illustrates this in action: <?php // extract substring // output: 'come' $str = 'Welcome to nowhere'; echo substr($str, 3, 4); ?> To extract a substring from the end of a string (rather than the beginning), pass substr() a negative offset, as in this revision of the preceding example: <?php // extract substring // output: 'come here' $str = 'Welcome to nowhere'; echo substr($str, 3, 5) . substr($str, -4, 4); ?> Formatting Strings PHP’s trim() function can be used to remove leading or trailing whitespace from a string; this is quite useful when processing data entered into a Web form. Here’s an example: <?php // remove leading and trailing whitespace // output 'a b c' $str = ' a b c '; echo trim($str); ?> Changing the case of a string is as simple as calling the strtolower() or strtoupper() function, as illustrated in the next listing: <?php // change string case $str = 'Yabba Dabba Doo'; // output: 'yabba dabba doo' echo strtolower($str); // output: 'YABBA DABBA DOO' echo strtoupper($str); ?> You can also uppercase the first character of a string with the ucfirst() function, or format a string in “word case” with the ucwords() function. The following listing demonstrates both these functions: <?php // change string case $str = 'the yellow brigands'; // output: 'The Yellow Brigands' echo ucwords($str); // output: 'The yellow brigands' echo ucfirst($str); ?>