410 likes | 579 Views
PHP Basics - 2. PHP Functions: Testing Variables. As the appearance of the variable does not show what variable it contains , many times in your scripts you won't be sure if the variable contains a value, or even if it exists at all . . isset( )
E N D
PHP Functions: Testing Variables As the appearance of the variable does not show what variable it contains , many times in your scripts you won't be sure if the variable contains a value, or even if it exists at all . • isset( ) • This function tests whether a variable has any value, including an empty string. It returns a value of either true or false. • empty( ) • It is same as isset( ) function. It tests true if a variable is not set, contains an empty string or has a value of 0. • is_int( ) • This tests whether a variable is an integer. • Example: • <?php • $a = 10; • echo isset($a); • echo "<br/>"; • echo is_int($a); • ?> 2
Testing Variables is_double( ) It tests whether a variable is floating-point number. is_string( ) It tests whether a variable is a text string. is_array( ) It tests whether a variable is an array. is_bool( ) It tests whether a variable is boolean. is_object( ) Returns true if the variable is an object. gettype( ) It will tell you the type of variable you have. 3
Changing Variable Types • PHP does not require explicit type definition in variable declaration. • A variable's type is determined by the context in which that variable is used. • If you assign a string value to variable $my_var, $my_var becomes a string. • If you then assign an integer value to $my_var, it becomes an integer. • There are ways to change the type of any variable: • Using settype( ) • Type casting • Using the functions intval( ), doubleval( ) and stringval( ) 4
Changing Variable Types: settype Example: <?php $my_var = 1995; echo $my_var . "<br/>"; echo "The variable \$my_var is now a " . gettype($my_var) . "<br/>"; settype($my_var,"string"); echo $my_var . "<br/>"; echo "The variable \$my_var is now a " . gettype($my_var) . "<br/>"; ?> Output: 1995 The variable $my_var is now a integer 1995 The variable $my_var is now a string 5
Changing Variable Types: settype Possibles values for the settype() function are: "boolean" (or, since PHP 4.2.0, "bool") "integer" (or, since PHP 4.2.0, "int") "float" (only possible since PHP 4.2.0, for older versions use the deprecated variant "double") "string" "array" "object" "null" (since PHP 4.2.0) The settype() function returns TRUE on success or FALSE on failure. This is important, for example, if you want to conditionally execute some code based on the success or failure of the settype() function. 6
Changing Variable Types: Type Casting Type casting in PHP works much as it does in C: the name of the desired type is written in parentheses before the variable which is to be cast. For example: <?php $a = 1; echo "\$a is a " . gettype($a) . "<br />\n"; $b = (string) $a; echo "\$b is a " . gettype($b) . "<br />\n"; ?> The approach above forces the variable value to change to the type indicated prior to assignment and only for the purposes of the assignment operation. A cast does not change the variable’s type permanently. 7
Type Casting (ctd) The casts allowed in PHP are: (int), (integer) - cast to integer (bool), (boolean) - cast to boolean (float), (double), (real) - cast to float (string) - cast to string (array) - cast to array (object) - cast to object Some alternative casts are shown above. 8
PHP Variable Handling Here are some examples that illustrate PHP's flexibility with respect to variable type: <?php $my_var1 = 20; echo $my_var1 . "<br>"; echo "The variable \$my_var1 is a " . gettype($my_var1) . "<br>"; $my_var2 = "5"; echo $my_var2 . "<br>"; echo "The variable \$my_var2 is a " . gettype($my_var2) . "<br>"; $my_var3 = $my_var1 * $my_var2; echo $my_var3 . "<br>"; echo "The variable \$my_var3 is a " . gettype($my_var3) . "<br>"; $my_var4 = $my_var1 . $my_var2; echo $my_var4 . "<br>"; echo "The variable \$my_var4 is a " . gettype($my_var4) . "<br>"; ?> Basically, PHP assumes that you know what you want to do and changes the variable type to allow you to do it. 9
PHP Variable Variables! Sometimes it is convenient to be able to have variable variable names. That is, a variable name which can be set and used dynamically. A normal variable is set with a statement such as: $a = "hello"; A variable variable takes the value of a variable and treats that as the name of a variable. In the above example, hello, can be used as the name of a variable by using two dollar signs. i.e. $$a = "world"; Creates a variable called $hello=“world” 10
PHP Variable Variables (ctd) • At this point two variables have been defined and stored in the PHP symbol tree: $a with contents "hello" and $hello with contents "world". Therefore, this statement: • echo "$a ${$a}"; • produces the exact same output as: • echo "$a $hello"; • i.e. they both produce: hello world. • In order to use variable variables with arrays, you have to resolve an ambiguity problem. That is, if you write $$a[1] then the parser needs to know if you meant to use $a[1] as a variable, or if you wanted $$a as the variable and then the [1] index from that variable. • The syntax for resolving this ambiguity is: ${$a[1]} for the first case and ${$a}[1] for the second. 11
PHP Operators • There are many operators used in PHP, just as is the case in other programming languages. • To make it easier to learn them all, we have separated the PHP operators into categories as follows: • Arithmetic Operators • Assignment Operators • Comparison Operators • Logical Operators • String Operators • Bitwise Operators 12
Arithmetic Operators Artihmetic operators generally mirror those available in C. 13
Arithmetic Operators: Example The PHP code segment below illustrates some of the basic arithmetic operations. <?php $addition = 2 + 4; $subtraction = 6 - 2; $multiplication = 5 * 3; $division = 15 / 3; $modulus = 5 % 2; echo "addition: 2 + 4 = " . $addition . "<br />"; echo "subtraction: 6 - 2 = " . $subtraction . "<br />"; echo "multiplication: 5 * 3 = " . $multiplication . "<br />“; echo "division: 15 / 3 = " . $division . "<br />"; echo "modulus: 5 % 2 = " . $modulus . "<br />"; ?> 14
Arithmetic Operators: Example You can also specify whether you want the increment to occur while the line of code is being executed or after the line has executed. The PHP code segment below illustrates the difference. <?php $x = 4; echo "The value of x with post-incrementing = " . $x++; echo "<br /> The value of x after the post-increment is " . $x; $x = 4; echo "<br /> The value of x with with pre-incrementing = " . ++$x; echo "<br /> The value of x after the pre-increment is " . $x; ?> 15
Assignment Operators The basic assignment operator is the equal symbol ( = ). This operator can be "read" as "the left operand is assigned the value of the expression on the right" or "the left operand gets set to the value of the expression on the right." The table below lists all of the PHP operators that combine assignment with arithmetic. 16
Assignment Operators: Example Example: <?php $counter = 8; $counter = $counter + 1; echo $counter; ?> However, there is a shorthand version for incrementing that uses one of the assignment operators above. We could write: <?php $counter = 8; $counter += 1; echo $counter; ?> 17
Assignment Operators: Example To add one to a variable or "increment" we could use the ++ operator. Thus, we have three possible approaches to incrementing: <?php $x = 15; $x++; echo $x; $x += 1; echo $x; $x = $x + 1; echo $x; ?> PHP's assignment operators enable you to create more concise code. The following example illustrates this feature. <?php $my_var = 12; $my_var += 14; // $my_var now equals 26 $my_var -= 12; // $my_var now equals 14 $my_var *= 10; // $my_var now equals 140 $my_var /= 7; // $my_var now equals 20 $my_var %= 6; // $my_var now equals 2 ?> 18
Assignment Operators: Example An assignment expression is replaced by its value. Thus, the value of the assignment expression $a = 3 is 3. This allows you to do some interesting things. Example: <?php /* note that $a and $b are used without declaration or initialization */ $a = ($b = 3) + 5; // $b has been set to 3, $a has been set to 8 echo "\$a = $a <br/>\n"; echo "\$b = $b <br/>\n"; ?> 19
Comparison Operators Comparison operators are used to compare expressions (e.g., values, variables) in a Boolean manner. This means that an expression constructed with comparison operators will return either true or false. 20
Comparison Operators (ctd) Comparison Operator Values: True will display as the integer one ( 1 ) and false will display as the empty string. The following values are evaluated as false: the integer zero ( 0 ) the float zero ( 0.0 ) the empty string ( "" ) the string zero ( "0" ) an array with zero elements an object with zero member variables NULL All other values are evaluated as true. 21
Logical Operators Logical operators allow you to combine the results of multiple comparison expressions to return a single value that evaluates to either true or false. 22
String Operators PHP has only two string operators (actually, only one with the second being a derivative of the first). The string operators are shown in the table below. 23
Bitwise Operators Bitwise operators are used in connection with logical operations and binary math. These operators directly affect the binary or ASCII representations of stored data. 24
Operator Precedence The order of precedence establishes a "priority" for operators, where those with the highest priority will be evaluated first. When there are several operators of the same priority, they will be processed from left to right if they are left associative, and right to left if they are right associative. 25
Operator Precedence: Example You can override the order of precedence but enclosing part of an expression in parentheses. The innermost parentheses are processed first, so that: (7 - 4) + 1 will give a result of 4 7 - (4 + 1) will give a result of 2 2 + 3 * 3 will give a result of 11 2 + (3 * 3) will also give 11 (2 + 3) * 3 will give a result of 15 1 + 3 + 3 * 2 will give a result of 10 1 + ((3 + 3) * 2) will give a result of 13 (1 + (3 + 3)) * 2 will give a result of 14 It is recommended that you use parentheses whenever you create a complex expression (even if not needed) so that it is easier for you and others to see what is going on when you read the code itself. 26
Control Structures • Control Structures are at the core of programming logic. • They allow a PHP script to alter the normal top-to-bottom order of execution for program code. In other words, the script can react differently depending on what has already occurred, or based on user input, and allow the graceful handling of repetitive tasks. • The two basic control structures, present in any procedural language, are branching and looping. • Branching allows the program to select between two or more alternative blocks of code. • The if and switch ... case statements are used for branching. • Looping (also known as iteration) allows the program to repeat a block of code, either a fixed number of times or until a conditional expression evaluates to a desired value. • The for and while statements are used for looping. 27
If Statement The if statement is the most fundamental control structure in any programming language. Its function is to execute a statement or block of statements if and only if the comparison expression provided to it evaluates to true. if (conditions) { // Code if condition is true } That is, the if statement "guards" a statement that is either executed or not ... based on the value of the expression 28
If Then Else Statement A variation on the basic if is the if ... then ... else statement. This variation selects between two alternative statements as illustrated below. if (conditions) { // Code if condition is true } else { // Code if condition is false } 29
Examples We can use comparison operators and logical operators in if statements that are more complex then which we have seen at the beginning of this chapter. Example -1 : if ($num1 == 1 && $num2 <=5 && !empty($num3) { // enter your code here } Example-2: if ($a > $b) { print "a is bigger than b"; } else { print "a is NOT bigger than b"; } 30
If … ElseIf Statement Like else, the elseif statement extends an if statement to execute a different statement in case the original if expression evaluates to false. However, unlike else, it will execute that alternative expression only if the elseif conditional expression evaluates to true. if ($a > $b) { print "a is bigger than b"; } elseif ($a == $b) { print "a is equal to b"; } else { print "a is smaller than b"; } 31
Alternative If Statements You can write if statements in a couple of different ways. The first simply substitutes a colon for the opening curly brace and the word endif with a semicolon for the closing curly brace. Example: if (condition1) : statement1; elseif (condition2): statement2; else: statement3 endif; The other alternative if structure is Ternary Operator, represented by question mark character ( ? ). This character can be used as shorthand for simple if/else Statements. It can only be used in situations where you want to execute a single expression based on whether a single condition evaluates to true or false. Example: (condition) ? (executes if the condition is true) : (executes if the condition is false); Note that this is a single statement, with the semicolon at the end. 32
Switch Statement The switch statement is similar to a series of IF statements on the same expression. In many occasions, you may want to compare the same variable (or expression) with many different values, and execute a different piece of code depending on which value it equals to. This is exactly what the switch statement is for. switch ($i) { case 0: print "i equals 0"; break; case 1: print "i equals 1"; break; default: print “Unexpected value for \$i"; } 33
While Loop • While tells PHP to execute the nested statement (s) repeatedly, as long as the while expression evaluates to true. The value of the expression is checked each time at the beginning of the loop. Example: • while (condition) • { • //code to execute • } • Example: • $a=0; • While ($a<=10) • { • echo “$a <br> \n”; • $a++; • } 34
Do … While Loop • It is same as while loop discussed above. The only difference is that the condition is tested after the code in question has been executed once . • do • { • // code to be used here • } while (condition) ; • Example: • $a=0; • do • { • echo “$a <br> \n”; • $a++; • } while ($a<=10); 35
For Loop The for loop takes three expressions. The first one is initialization condition, second is condition that is evaluated in each iteration; if this condition is false than the loop will end, and the third expression is executed in every iteration. Example: for ($i = 0 ; $i <= 10 ; $i++) { echo $i. "<br>\n" ; } The first time, value of i = 0, so 0 will be printed and further 1 to 10 will be printed as value of i is incremented by 1 in each iteration. 36
Foreach Loop PHP 4 (not PHP 3) includes a foreach construct, much like Perl and some other languages. This simply gives an easy way to iterate over arrays. There are two syntaxes; the second is a minor but useful extension of the first: foreach(array_expression as $value) statement foreach(array_expression as $key => $value) statement The first form loops over the array given by array_expression. On each loop, the value of the current element is assigned to $value and the internal array pointer is advanced by one (so on the next loop, you'll be looking at the next element). The second form does the same thing, except that the current element's key will be assigned to the variable $key on each loop (for associative arrays). 37
Foreach Loop: Example • $names= array(“Jay”, “Brad”, “Ernie”, “John”); • foreach($names as $i) • { • echo $i . “<br> \n”; • } • Output: • JayBradErnieJohn 38
“continue” in Loops • Continue is used within looping structures to skip the rest of the current loop iteration and continue execution at the beginning of the next iteration. • Continue accepts an optional numeric argument which tells it how many levels of enclosing loops it should skip to the end of. • Example : • $i = 0; • while ($i++ < 5) • { • echo "Outer-”.$i.”<br>\n"; • while (1) • { echo "Middle<br>\n"; • while (1) • { echo "Inner<br>\n"; • continue 3; • } • echo "This never gets output.<br>\n"; • } • echo "Neither does this.<br>\n";} Output: Outer-1MiddleInnerOuter-2MiddleInnerOuter-3MiddleInnerOuter-4MiddleInnerOuter-5MiddleInner 39
“break” in Loops break ends execution of the current for , foreach , while , do..while or switch structure. break accepts an optional numeric argument which tells it how many nested enclosing structures are to be broken out of. Example: $i = 0; while (++$i) { switch ($i) { case 5: echo "At 5<br>\n"; break 1; /* Exit only the switch. */ case 10: echo "At 10 quitting<br>\n"; break 2; /* Exit the switch and the while. */ default: break; } } 40