Chapter 2 - Gaining Control with Operators and Flow Control spring into PHP 5 by Steven Holzner Slides were developed by Jack Davis College of Information Science and Technology Radford University 1 PHP Operators and Flow Control • Math Operators + * / % Adds numbers Subtracts numbers Multiplies numbers Divides numbers returns integer remainder from integer division <?php echo "5+2 = ", 5+2, "<br />"; ?> • Math Functions abs Absolute Value You call functions the same as you do in most languages. Use the name of the function and provide the appropriate arguments. $y = abs(-9); echo "$y"; 2 List of Math Functions • Here's some of the commonly used functions. More are listed in the text, p. 35. ceil rounds fractions up exp calculates the exponent of e floor rounds fractions down fmod returns the floating point remainder of the division of the arguments is_nan determines whether a value is not a number max finds the highest value min finds the lowest value sqrt square root 3 Assignment Operator • As in most languages the assignment operator is =. This means the expression on the right of the operator is evaluated and the resulting value is stored in the variable on the left. $a = 4 + 3 + $b. • There are also combined assignment operators. += -+ *= /= .= %= |= ^= <<= >>= $a += $b; We'll see more of these in use later. 4 Incrementing & Decrementing • PHP includes the ++ and the -- operators that can be used pre and post for some operation. ++$value increments $value by one, then returns $value --$value decrements $value by one, then returns $value $value++ returns $value, then increments $value-- returns $value, then decrements <?php $a = $b = $c = $d = 1; echo "\$a++ gives ", $a++, "<br />"; echo "++\$b gives ", ++$b, "<br />"; ?> ouputs what ? 5 Operator Precedence • new • [ • ! ~ ++ -(int) (float) (string) (array) (object) • @ • * / % • + . • << >> • < <= > >= • == != === !== • & • ^ • | • && • || • ? : • = += -+ and so on there are more. use parentheses to avoid problems. 6 Execution Operator • The execution operator lets you run operating system commands and programs, enclose the command in backquotes (`). <?php $output = `date`; echo $output; ?> In a Unix system using bash -Fri Aug 25 12:30:42 EDT 2006 • you can pass an argument to the system command <?php $output = `ls -l *.php`; echo $output; ?> • https://php.radford.edu/~jcdavis/it325example s/execop.php 7 String Operators • PHP has two string operators. concatenation . concatenating assignment .= • <?php $a = "ITEC"; $b = 325; $c = $a . " " . $b; #note coercion # now $c = "ITEC 325" $a .= " " . $b; // now $a = "ITEC 325" ?> • we'll see many more string function in PHP in the next chapter 8 Bitwise Operators • PHP has a set of operators that can work with the individual bits in an integer. Note - Besides integers, you can also work with strings using these operators; in that case, the ASCII value of each character is used. & AND $a & $b bits set in both $a and $b are set | OR $a | $b bits set in either $a or $b are set ^ Xor $a ^ $b bits set in either $a or $b but not both are set - Not - $a bits set in $a are not set and vice versa << shift left $a << $b shift left the bits in $a by the amount in $b -- if $b is one, multiply by two >> shift right $a >> $b shift right the bits in $a by the amount in $b -- if $b is one, divide by two 9 if Statements • Just the standard if (boolean expression) php statement; if the boolean expression evaluates to true the statement beneath is executed, otherwise it is not executed can execute more than one statement by createing a block of statements using { } if (boolean expression) { phpstatement 1; php statement 2; php statement 3; } $a = 50; if ($a > 45) echo "\$a's value is: $a"; 10 Comparison Operators == equal $a == $b TRUE, if $a equals $b === Identical $a === $b TRUE, if $a is identical to $b (no coercions) != not equal $a != $b TRUE, if $a is not equal to $b <> not equal $a <> $b TRUE, if $a is not equal to $b !== not identical $a !== $b TRUE, if $a is not identical to $b (no coercions) < less than $a < $b TRUE, if $a is less than $b > greater than $a > $b TRUE, if $a is greater than $b <= less than or equal $a <= $b TRUE, if $a is less than or equal to $b >= greater than or equal $a >= $b TRUE, if $a is greater than or equal to $b 11 Logical Operators and And $a and $b TRUE, if both $a and $b are true or Or $a or $b TRUE, if $a or $b are true xor Xor $a xor $b TRUE, if either $a or $b is true, but not both ! Not !$a TRUE, if $a is false && And $a && $b TRUE, if both $a and $b are true (higher precedence than and) || Or $a || $b TRUE, if either $a or $b is true (higher precedence than or) 12 else and elseif • $a = 20; $b = 40; $c = "40chairs"; if ($a >= $b) { echo "\$a is larger, value is : $a"; } else { echo "\$b is larger, value is : $b";} if ($a == $c) { echo "a & c are the same."; } else { echo "a & c are not the same."; } if ($a === $c) { echo "a & c are the same."; } elseif ($a == $c) { echo "a & c are different types."; } else {echo "a & c have different values."} • comparisons of strings and characters are based on the ASCII character codes 13 switch Statements • switch statements are used for testing multiple conditions. The same tests can be built with multiple if statements, however, switch statements help to organize code. (use ints, floats, or strings) $temp = 70; switch ($temp) { case 70: echo "Nice weather."; break; case 80: { echo "Warm today. <br />"; echo "Old bones like warm weather."; break; } case 90: echo "Hot!!!"; break; default: echo "temperature not in range"; } 14 for Loops • for (expression1;expression2;expression3) statement; for ($ctr = 1; $ctr < 10; $ctr++) { print ("\$ctr = : $ctr <br />"); } • expressions in a for loop can handle multiple indexes, as long as you separate them with the comma operator. for ($var1=2, $var2=2; $var1<5; $var1++) { echo "var1 is : $var1 ", " double it : $var1 * $var2 ": } • probably easier to use nested for loops 15 while Loops • standard loop that keeps executing until the initial condition is false $ind = 10; while ($ind > 1) { echo "ind = $ind"; $ind--; } • often used when reading files open_file(); while (not_at_end_of_file()) { $data = read_one_line_from_file(); echo $data; } 16 do … while Loops • just like a while loop except the condition is checked at the end of the loop instead of the beginning, so it's always executed at least once do { echo $val, "<br />"; $val *= 2; } while ($val < 10); 17 foreach Loops & break • the foreach loop makes working with arrays much easier. <?php $arr = array("apples","oranges","grapes"); foreach ($arr as $value) { echo "Current fruit: $value <br />"; } • in case you want to stop a loop or swich statement early, the break statement ends execution of the current for, foreach, while, do…while, or switch statement. while (not_at_end_of_file()) { $data = read_one_line_from_file(); echo $data; if ($data == "quit") break; } 18 continue Statement • the continue statement can be used inside a loop to skip the rest of the current loop iteration and continue with the next iteration. for ($val = -2; $val < 2; $val++) { if ($val == 0) { continue; } echo 1/$val, " <br />"; } skipped the division by 0 • php has alternate syntax for if, while, for, foreach, and switch statements for ($ctr=0; $ctr < 5; $ctr++): echo "Print this five times."; endfor; 19