itm 352 - © port, kazmanvariables - 1 itm 352 expressions, precedence, working with strings

26
ITM 352 - © Port, Kazman Variables - 1 ITM 352 Expressions, Precedence, Working with Strings

Upload: griselda-lyons

Post on 04-Jan-2016

221 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: ITM 352 - © Port, KazmanVariables - 1 ITM 352 Expressions, Precedence, Working with Strings

ITM 352 - © Port, Kazman Variables - 1

ITM 352

Expressions, Precedence, Working with Strings

Page 2: ITM 352 - © Port, KazmanVariables - 1 ITM 352 Expressions, Precedence, Working with Strings

ITM 352 - © Port, Kazman Variables - 2

Review: What is a PHP File? PHP files have extension ".php”

A PHP file can contain text, CSS, HTML, JavaScript and, of course, PHP code.

PHP code is executed on the server, and the result is returned to the browser as plain text. If that text has HTML, CSS, or JavaScript it will be interpreted as configured by the browser (client).

PHP code will not be present in the “source” on the browser because it was already executed on the server. That that is, only the output from executing the PHP file on the server is given to the browser.

Let’s see this for ourselves (again). Try this in a junk.php file then “view page source” after accessing it through a browser:

Did you know the sqrt(2) is about <?php print sqrt(2) ?>

Did you see any PHP code? Can you see what was executed and outputted versus what was just “passed through” the PHP interpreter?

Page 3: ITM 352 - © Port, KazmanVariables - 1 ITM 352 Expressions, Precedence, Working with Strings

ITM 352 - © Port, Kazman Variables - 3

Review: What is a PHP Program?

A PHP program starts with

<?php and ends with

?> In between is a series of statements in the PHP

language. This is a PHP block You can have as many PHP block’s as you want. Anything else, before or after, is NOT interpreted

by PHP and is passed though unprocessed as plain text.

Page 4: ITM 352 - © Port, KazmanVariables - 1 ITM 352 Expressions, Precedence, Working with Strings

ITM 352 - © Port, Kazman Variables - 4

Review: What is a PHP Statement?A PHP programs normally contain

comments and code (statements)Comments:

start with // or # (single line) or begin with /* and end with */ (multiple lines)

Statements MUST end with a ; The most common error is forgetting the ;

Let’s take a look at the most common types of statements…

Page 5: ITM 352 - © Port, KazmanVariables - 1 ITM 352 Expressions, Precedence, Working with Strings

ITM 352 - © Port, Kazman Variables - 5

Expressions

Expressions are PHP statements that return values and use operators the value produced by an expression when evaluated is "returned", i.e. it is the

statement's "return value."

$numberOfBaskets = 5; // assignment returns 5

$eggsPerBasket = 8;

$totalEggs = $numberOfBaskets * $eggsPerBasket; In the first two lines when the assignment operation is evaluated the

expression returns the value 5 for the first line and 8 for the second $numberOfBaskets * $eggsPerBasket is an expression that returns

the integer value 40 $check = ($totalEggs = $numberOfBaskets *

$eggsPerBasket) / 40;

Similarly, functions return values (more on this later…)

How many Expressions

does this statement

have??

Page 6: ITM 352 - © Port, KazmanVariables - 1 ITM 352 Expressions, Precedence, Working with Strings

ITM 352 - © Port, Kazman Variables - 6

OperatorsOperators take operands and perform some

operation There are unary, binary, and tertiary operators

that use 1, 2, and 3 operands respectively. Examples:

Unary: $endOfFile++, !is_string()Binary: 2 * 3, $a % 3, $a = 40,$a > 3, $a == 5, $a || $b

Usually arithmetic, but can be other operationsSee next slide for example…

Page 7: ITM 352 - © Port, KazmanVariables - 1 ITM 352 Expressions, Precedence, Working with Strings

ITM 352 - © Port, Kazman Variables - 7

Simple Expressions PHP will interpret operations between different

data types according to certain casting rules and precedence $whatIsThis = 1.2 + " Fred" . 0777 * true; Our goal is to understand why the value of the above expression

is 1.2511 (after the next bunch of slides you will!).

The same variable can appear on both sides of the assignment operator $a = $a + 1; // add 1 to value in $a and set in $a

This is unlike algebra and actually very useful!

Can you see why this is useful?

Page 8: ITM 352 - © Port, KazmanVariables - 1 ITM 352 Expressions, Precedence, Working with Strings

ITM 352 - © Port, Kazman Variables - 8

Operators and Precedence (Partial)

Associativity Operators

non-associative ++ --

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

right !

left * / %

left + - .

non-associative < <= > >= <>

non-associative == != === !==

left &&

left ||

Precedence

Page 9: ITM 352 - © Port, KazmanVariables - 1 ITM 352 Expressions, Precedence, Working with Strings

ITM 352 - © Port, Kazman Variables - 9

Operator Precedence and Parentheses

Expressions follow certain rules that determine the order an expression is evaluated e.g. should 2 + 3 * 4 be 5*4 or 2+12?

PHP operators have precedence similar to algebra to deal with this Operators with higher preference are evaluated first

Ex. In the expression 2 + 3*4, the * operator has higher precedence than + so 3*4 is evaluated first to return the value 12, then the expression 2 + 12 is evaluated to return 14

Use parentheses '( )' to force evaluation for lower precedence Ex. (2 + 3)*4

Do not clutter expressions with parentheses when the precedence is correct and obvious!

Page 10: ITM 352 - © Port, KazmanVariables - 1 ITM 352 Expressions, Precedence, Working with Strings

ITM 352 - © Port, Kazman Variables - 10

PrecedenceAn example of precedence rules to illustrate which operators in the following expression should be evaluated first:

$score < $min/2 – 10 || $score > 90 Division operator has highest precedence of all operators used here so we

show it as if it were parenthesized:$score < ($min/2) – 10 || $score > 90 Subtraction operator has next highest precedence :$score < (($min/2) – 10) || $score > 90 The < and > operators have equal precedence and are evaluated left-to-right:($score < (($min/2) – 10)) || ($score > 90)

This is a fully parenthesized expression that is equivalent to the original. It shows the order in which the operators in the original will be evaluated.

Page 11: ITM 352 - © Port, KazmanVariables - 1 ITM 352 Expressions, Precedence, Working with Strings

ITM 352 - © Port, Kazman Variables - 11

Operator Associativity

Some operators have the same precedence order. Ex. Is 4 / 2 *3 first evaluated 4 / 6 or 2 * 3 ?

In such cases, the associativity determines the order of evaluation The / and * operators are left-associative and so

the operations are performed from left to right4 / 2 is first, returning 2, then 2 * 3 returning 6

Page 12: ITM 352 - © Port, KazmanVariables - 1 ITM 352 Expressions, Precedence, Working with Strings

ITM 352 - © Port, Kazman Variables - 12

Examples of Arithmetic Precedence

Ordinary Math Expression

PHP Expression (preferred form)

PHP Fully Parenthesized Expression

rate2 + delta $rate*$rate + $delta ($rate*$rate) + $delta

2(salary + bonus) 2 * ($salary + $bonus) 2 * ($salary + $bonus)

3mass time

1

1/($time + 3 * $mass) 1/($time + (3 *$mass))

9v t

7 - a

($a - 7) / ($t + 9 * $v) ($a - 7) / ($t +( 9 * $v))

Do Lab Exercise #1

Page 13: ITM 352 - © Port, KazmanVariables - 1 ITM 352 Expressions, Precedence, Working with Strings

ITM 352 - © Port, Kazman Variables - 13

Casting: Changing the Data Type of the Returned Value

Casting is the process of converting from one data type to another data type. This can be useful.

Casting only changes the type of the returned value (the single instance where the cast is done), not the type of the variable

For example:$n = 5.0;$x = (int) $n;

Since $n is a float, (int) $n converts the value to an int, now $x is an integer type.

Page 14: ITM 352 - © Port, KazmanVariables - 1 ITM 352 Expressions, Precedence, Working with Strings

ITM 352 - © Port, Kazman Variables - 14

Implicit Type Casting Casting is done implicitly (automatically) when a "lower"

type is assigned to a "higher" type, depending on the operator

The data type hierarchy (from lowest to highest):bool int double string array object

For example:$x = 0;$n = 5 + 10.45;$x = $n; the value 5 is cast to a double, then assigned to $n $x now is a double This is called implicit casting because it is done

automatically.

Page 15: ITM 352 - © Port, KazmanVariables - 1 ITM 352 Expressions, Precedence, Working with Strings

ITM 352 - © Port, Kazman Variables - 15

Data Types in an Expression: More Implicit Casting

Some expressions have a mix of data types All values are automatically elevated (implicitly cast) to

the highest level before the calculation For example:

$n = 2;$x = 5.1;$y = 1.33;$a = (n * x)/y;

$n is automatically cast to type double before performing the multiplication and division

Page 16: ITM 352 - © Port, KazmanVariables - 1 ITM 352 Expressions, Precedence, Working with Strings

ITM 352 - © Port, Kazman Variables - 16

Casting: Changing the Data Type of the Returned Value

Casting is the process of converting from one data type to another data type. This is sometimes useful.

Casting only changes the type of the returned value (the single instance where the cast is done), not the type of the variable

For example:$n = 5.0;$x = (int) $n;

Since $n is a float, (int) $n converts the value to an int, now $x is an integer type.

** WARNING ** Odd things can happen when casting from a higher to a lower type:$low = (int) 5.2345; // returns 5$high = (int) 5.999; // returns 5

So why does 1.2 + " Fred" . 0777 * true evaluate to 1.2511?

Page 17: ITM 352 - © Port, KazmanVariables - 1 ITM 352 Expressions, Precedence, Working with Strings

ITM 352 - © Port, Kazman Variables - 17

Increment and Decrement Operators Shorthand notation for common arithmetic operations used for

counting (up or down) The counter can be incremented (or decremented) before or after using

its current value++$count; // preincrement: $count = $count + 1 before using it $count++; // postincrement: $count = $count + 1 after using it--$count; // predecrement: $count = $count - 1 before using it$count--; // postdecrement: $count = $count - 1 after using it

You can also increment and decrement non-integers $var = 'a'; $var++; // $var now 'b' What if $var = 'az' ?

Page 18: ITM 352 - © Port, KazmanVariables - 1 ITM 352 Expressions, Precedence, Working with Strings

ITM 352 - © Port, Kazman Variables - 18

Increment/Decrement Operator Examples

Common code:

$n = 3;$m = 4;

What will be the value of m and result after each of these executes?

(a) $result = $n * ++$m;//preincrement $m(b) $result = $n * $m++;//postincrement $m(c) $result = $n * --$m;//predecrement $m(d) $result = $n * $m--;//postdecrement $m

Do Lab Exercise #2

Page 19: ITM 352 - © Port, KazmanVariables - 1 ITM 352 Expressions, Precedence, Working with Strings

ITM 352 - © Port, Kazman Variables - 19

Specialized Assignment Operators A shorthand notation for performing an operation on and assigning a

new value to a variable

General form: $var <op>= expression; equivalent to: $var = $var <op> (expression); Where <op> is +, -, *, /, %, . , |, ^, ~, &, <<, >>

Examples:$amount += 5;

//same as $amount = $amount + 5;$amount *= 1 + $interestRate;

//$amount = $amount * (1 + $interestRate); Note that the right side is treated as a unit

Do Lab Exercise #3

Page 20: ITM 352 - © Port, KazmanVariables - 1 ITM 352 Expressions, Precedence, Working with Strings

ITM 352 - © Port, Kazman Variables - 20

Single vs. Double Quotes vs. Heredoc Three ways to declare a string value

Single quotes 'So this is Christmas?';

Double quotes "How about Kwanza?";

Here Documents

<<< When_Will_It_EndIt was a dark and stormy night, my son said, "Dad, tell me a story" so I said, "It was a dark and stormy night, my son said, "Dad, tell me a story" so I said, "It was a dark and stormy night, my son said, "Dad, tell me a story" so I said,

When_Will_It_End

Page 21: ITM 352 - © Port, KazmanVariables - 1 ITM 352 Expressions, Precedence, Working with Strings

ITM 352 - © Port, Kazman Variables - 21

Strings Any sequence of characters e.g. abc123$%!

In PHP these are referred to as string Designated as a literal by single or double quotes

'string', "string" Note: Any variables inside a double quoted string are

expanded into that string, single quoted strings are not expanded

$a = 10; echo "I have $a more slides";I have 10 more slides

$a = 10; echo 'I have $a more slides';I have $a more slides

Page 22: ITM 352 - © Port, KazmanVariables - 1 ITM 352 Expressions, Precedence, Working with Strings

ITM 352 - © Port, Kazman Variables - 22

Escape Sequences

To use characters in strings that can't be typed or seen or are interpreted specially by php (such as $, {,},\, etc.) there are escape sequences \n newline (note: not the same as HTML <br>) \t tab \$ the $ character \\ the \ character

Example: echo "I need more \$ but they \\'ed the budget\n";

I need more $ but they \'ed the budget

Page 23: ITM 352 - © Port, KazmanVariables - 1 ITM 352 Expressions, Precedence, Working with Strings

ITM 352 - © Port, Kazman Variables - 23

What's the Difference?

The way you declare a string will affect how Escape codes (e.g. \n ) are recognized; variables are interpreted

Single quotes are literal $variable = 10;echo 'This prints $variable\n';

This prints $variable\n All characters print as written, No escape codes are recognized

except \' and \\

Double quotes expand variable values and escape characters $variable = 10;echo "This prints $variable\n";

This prints 10

Page 24: ITM 352 - © Port, KazmanVariables - 1 ITM 352 Expressions, Precedence, Working with Strings

ITM 352 - © Port, Kazman Variables - 24

Heredoc

Multi-line string constants are easily created with a heredoc expression

$variable = 'Here Here!';$wind = <<< QUOTELine 1. \nLine 2. " "Line 3. ' 'Line 4. $variableQUOTE;echo $wind; Variables are expanded, escape characters are recognized

Do Lab Exercise #4

Page 25: ITM 352 - © Port, KazmanVariables - 1 ITM 352 Expressions, Precedence, Working with Strings

ITM 352 - © Port, Kazman Variables - 25

Concatenating (Appending) StringsThe '.' operator is used for string concatenation (merging two strings):

$name = "Mondo";$greeting = "Hi, there!";echo $greeting . $name . "Welcome";causes the following to display on the screen:

Hi, there!MondoWelcome

Note that you have to remember to include spaces if you want it to look right:$greeting . " " . $name . " Welcome";

causes the following to display on the screen:Hi, there! Mondo Welcome

Do Lab Exercise #5

Page 26: ITM 352 - © Port, KazmanVariables - 1 ITM 352 Expressions, Precedence, Working with Strings

ITM 352 - © Port, Kazman Variables - 26

Useful Tools: print_r(), var_dump()

You can easily output variable types and their values with print_r(), var_dump()

These functions are very useful for debugging your programs

print_r() displays just the value, var_dump() displays the type and value

Do Lab Exercise #6