php basics - 2

40
PHP Basics - 2

Upload: zoie

Post on 23-Feb-2016

39 views

Category:

Documents


1 download

DESCRIPTION

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( ) - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: PHP Basics - 2

PHP Basics - 2

Page 2: PHP Basics - 2

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 .

PHP Functions: Testing Variables

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

Page 3: PHP Basics - 2

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.

Testing Variables

3

Page 4: PHP Basics - 2

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

Page 5: PHP Basics - 2

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:1995The variable $my_var is now a integer1995The variable $my_var is now a string

5

Page 6: PHP Basics - 2

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

Page 7: PHP Basics - 2

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.

Changing Variable Types: Type Casting

7

Page 8: PHP Basics - 2

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. 

Type Casting (ctd)

8

Page 9: PHP Basics - 2

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.

PHP Variable Handling

9

Page 10: PHP Basics - 2

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”

PHP Variable Variables!

10

Page 11: PHP Basics - 2

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.

PHP Variable Variables (ctd)

11

Page 12: PHP Basics - 2

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

Page 13: PHP Basics - 2

Artihmetic operators generally mirror those available in C.

Operator Description Example Result$a + $b Addition $a=2

$a+24

$a - $b Subtraction $a=25-$a

3

$a * $b Multiplication $a=4$a*5

20

$a / $b Division 15/55/2

32.5

$a % $b Modulus(division remainder)

5%210%810%2

120

$a++ Increment $a=5$a++

$a=6

$a-- Decrement $a=5$a--

$a=4

Arithmetic Operators

13

Page 14: PHP Basics - 2

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 />"; ?>

Arithmetic Operators: Example

14

Page 15: PHP Basics - 2

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; ?>

Arithmetic Operators: Example

15

Page 16: PHP Basics - 2

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.

Operator Example Is The Same As= $x = $y; $x = $y;

+= $x += $y; $x = $x + $y;

-= $x -= $y; $x = $x - $y;

*= $x *= $y; $x = $x * $y;

/= $x /= $y; $x = $x / $y;

%= $x %= $y; $x = $x % $y;

Assignment Operators

16

Page 17: PHP Basics - 2

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; ?>

Assignment Operators: Example

17

Page 18: PHP Basics - 2

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; ?>

Assignment Operators: Example

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

Page 19: PHP Basics - 2

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"; ?>

Assignment Operators: Example

19

Page 20: PHP Basics - 2

Operator Description Example$a == $b is equal to 5==8 returns false

$a === $b is identical to 8===8 returns true

$a != $b is not equal 5!=8 returns true

$a <> $b is not equal 5!=8 returns true

$a !== $b is not identical 5!=="5" returns true

$a > $b is greater than 5>8 returns false

$a < $b is less than 5<8 returns true

$a >= $b is greater than or equal to 5>=8 returns false

$a <= $b is less than or equal to 5<=8 returns true

Comparison OperatorsComparison 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

Page 21: PHP Basics - 2

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.

Comparison Operators (ctd)

21

Page 22: PHP Basics - 2

Logical operators allow you to combine the results of multiple comparison expressions to return a single value that evaluates to either true or false. Operator Name Example$a && $b AND TRUE if both $a and $b are TRUE

$a=6; $b=3;($a < 10 && $b > 1) returns true

$a and $b AND TRUE if both $a and $b are TRUE$a=6; $b=3; ($a < 10 and $b > 1) returns true

$a || $b OR TRUE if either $a or $b is TRUE$a=6; $b=3;($a==5 || $b==3) returns true($a==5 || $b==5) returns false

$a or $b OR TRUE if either $a or $b is TRUE$a=6; $b=3; ($a==5 or $b==5) returns false

$a xor $b XOR TRUE if either $a or $b is TRUE, but not both$a=6; $b=3; ($a>5 xor $b<5) returns false

!$a NOT TRUE if $a is FALSE$a=6; $b=3; !($a==$b) returns true

Logical Operators

22

Page 23: PHP Basics - 2

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.

Operator Description Example$a . $b concatenation $a = "Hello ";

$b = $a . "World!"; assigns "Hello World" to $b

$a .= $b concatenation and assignment $a = "Hello ";$a .= "World!"; assigns "Hello World" to $a

String Operators

23

Page 24: PHP Basics - 2

Bitwise operators are used in connection with logical operations and binary math. These operators directly affect the binary or ASCII representations of stored data. Operator Description Result

$a & $b AND Bits that are set in both $a and $b are set

$a | $b OR Bits that are set in either $a or $b are set

$a ^ $b XOR Bits that are set in $a or $b but not both are set

~ $a NOT Bits that are set in $a are not set, and vice versa

$a << $b shift left Shift the bits of $a $b steps to the left (each step means "multiply by two")

$a >> $b shift right Shift the bits of $a $b steps to the right (each step means "divide by two")

Bitwise Operators

24

Page 25: PHP Basics - 2

Operator PrecedenceThe 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

Associativity Operators Additional Informationnon-associative ++ -- increment/decrement

non-associative ~ - (int) (float) (string) (array) (object) (bool) types

right ! logical left * / % arithmetic left + - . arithmetic and stringleft << >> bitwise non-associative < <= > >= <> comparison non-associative == != === !== comparison left & bitwise and referencesleft ^ bitwise left | bitwise left && logical left || logical right = += -= *= /= .= %= &= |= ^= <<= >>= assignment left and logical left xor logical left or logical

Page 26: PHP Basics - 2

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 112 + (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.

Operator Precedence: Example

26

Page 27: PHP Basics - 2

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

Page 28: PHP Basics - 2

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

If Statement

28

Page 29: PHP Basics - 2

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 }

If Then Else Statement

29

Page 30: PHP Basics - 2

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:

Examples

if ($a > $b) { print "a is bigger than b"; } else { print "a is NOT bigger than b"; }

30

Page 31: PHP Basics - 2

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"; }

If … ElseIf Statement

31

Page 32: PHP Basics - 2

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.

Alternative If Statements

32

Page 33: PHP Basics - 2

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"; }

Switch Statement

33

Page 34: PHP Basics - 2

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++;}

While Loop

34

Page 35: PHP Basics - 2

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);

Do … While Loop

35

Page 36: PHP Basics - 2

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.

For Loop

36

Page 37: PHP Basics - 2

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).

Foreach Loop

37

Page 38: PHP Basics - 2

$names= array(“Jay”, “Brad”, “Ernie”, “John”);foreach($names as $i) { echo $i . “<br> \n”;}

Output:JayBradErnieJohn

Foreach Loop: Example

38

Page 39: PHP Basics - 2

• 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";}

“continue” in Loops

39

Output:Outer-1MiddleInnerOuter-2MiddleInnerOuter-3MiddleInnerOuter-4MiddleInnerOuter-5MiddleInner

Page 40: PHP Basics - 2

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; } }

“break” in Loops

40