0% found this document useful (0 votes)
5 views

WebDevelopmet Lec3

The document discusses various PHP programming concepts including variables, data types, operators, control structures, and functions. Key points covered include PHP syntax for variables, strings, expressions, conditional logic, and loops as well as differences compared to other languages.

Uploaded by

Amr Hossam
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

WebDevelopmet Lec3

The document discusses various PHP programming concepts including variables, data types, operators, control structures, and functions. Key points covered include PHP syntax for variables, strings, expressions, conditional logic, and loops as well as differences compared to other languages.

Uploaded by

Amr Hossam
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 50

Science Calculations

System

System

C uses curly
braces { } for
code blocks.
Scripting/
Interpreted

http://en.wikipedia.org/wiki/History_of_programming_languages
Philosophy of PHP
• You are a responsible and intelligent programmer.
• You know what you want to do.
• Some flexibility in syntax is OK - style choices are OK.
• Let’s make this as convenient as possible.
• Sometimes errors fail silently.
<h1>Hello from Dr. Chuck's HTML Page</h1>
<p>
<?php
echo "Hi there.\n";
$answer = 6 * 7;
echo "The answer is $answer, what ";
echo "was the question again?\n";
?>
</p>
<p>Yes another paragraph.</p>
<h1>Hello from Dr. Chuck's HTML Page</h1>
<p>
<?php
echo "Hi there.\n";
$answer = 6 * 7;
echo "The answer is $answer, what ";
echo "was the question again?\n";
?>
</p>
<p>Yes another paragraph.</p>
PHP from the Command Line
• You can run PHP from the <?php
echo("Hello World!");
command line - the output
echo("\n");
simply comes out on the ?>
terminal.
• It does not have to be part
of a request-response cycle.
PHP Variables
• PHP variables
All PHP variables begin with the $
• Variable names can begin with an underscore
• Otherwise rules are similar to most other languages
Variables are dynamically typed
• No type declarations
Variables are BOUND or UNBOUND
>Unbound variables have the value NULL
Variable Names
• Start with a dollar sign ($) followed by a letter or underscore,
followed by any number of letters, numbers, or underscores
• Case matters

$abc = 12; abc = 12;


$total = 0; $2php = 0;
$largest_so_far = 0; $bad-punc = 0;

http://php.net/manual/en/language.variables.basics.php
Variable Name Weirdness
Things that look like variables but are missing a dollar sign can be
confusing.

$x = 2; $x = 2;
$y = x + 5; y = $x + 5;
print $y; print $x;

5 Parse error
Strings / Different + Awesome
• String literals can use single quotes or double quotes.
• The backslash (\) is used as an “escape” character.
• Strings can span multiple lines - the newline is part of the
string.
• In double-quoted strings, variable values are expanded.
• Concatenation is the "." not "+" (more later).
Comments in PHP ☺
echo 'This is a test'; // This is a c++ style comment
/* This is a multi line comment
yet another line of comment */
echo 'This is yet another test';
echo 'One Final Test'; # This is a shell-style comment
Output
• echo is a language construct - can <?php
$x = "15" + 27;
be treated like a function with
echo $x;
one parameter. Without echo("\n");
parentheses, it accepts multiple echo $x, "\n";
parameters. print $x;
print "\n";
• print is a function - only one print($x);
parameter, but parentheses are print("\n");
optional so it can look like a ?>
language construct.
Expressions
• Completely normal like other languages ( + - / * )
• More aggressive implicit type conversion

<?php
$x = "15" + 27;
echo($x); 42
echo("\n");
?>
Expressions
• Expressions evaluate to a value. The value can be a string,
number, boolean, etc.
• Expressions often use operations and function calls. There is
an order of evaluation when there is more than one operator
in an expression.
• Expressions can also produce objects like arrays.
Operators of Note
• Increment / Decrement ( ++ -- )
• String concatenation ( . )
• Equality ( == != )
• Identity ( === !== )
• Ternary ( ? : )
• Side-effect Assignment ( += -= .= etc.)
• Ignore the rarely-used bitwise operators ( >> << ^ | & )
Increment / Decrement
• These operators allow you to both retrieve and increment /
decrement a variable.
• They are generally avoided in civilized code.

$x = 12;
$y = 15 + $x++; x is 13 and y is 27
echo "x is $x and y is $y \n";
Increment / Decrement
• These operators allow you to both retrieve and increment /
decrement a variable.
• They are generally avoided in civilized code.

$x = 12;
$y = 15 + $x; x is 13 and y is 27
$x = $x + 1;
echo "x is $x and y is $y \n";
String Concatenation
PHP uses the period character for concatenation, because the
plus character would instruct PHP to do the best it could to add
the two things together, converting if necessary.

$a = 'Hello ' . 'World!'; Hello World!


echo $a . "\n";
Ternary
The ternary operator comes from C. It allows conditional
expressions. It is like a one-line if-then-else. Like all “contraction”
syntaxes, we must use it carefully.
$www = 123;
$msg = $www > 100 ? "Large" : "Small" ;
echo "First: $msg \n";
$msg = ( $www % 2 == 0 ) ? "Even" : "Odd";
echo "Second: $msg \n"; First: Large
$msg = ( $www % 2 ) ? "Odd" : "Even";
Second: Odd
echo "Third: $msg \n";
Third: Odd
Side-Effect Assignment
These are pure contractions. Use them sparingly.
$out = "Hello";
$out = $out . " ";
$out .= "World!";
$out .= "\n";
Hello World!
echo $out; Count: 1
$count = 0;
$count += 1;
echo "Count: $count\n";
Casting In PHP, division forces
operands to be floating
point. PHP converts
$a = 56; $b = 12;
expression values silently
$c = $a / $b;
echo "C: $c\n";
and aggressively.
$d = "100" + 36.25 + TRUE;
echo "D: ". $d . "\n";
echo "D2: ". (string) $d . "\n"; C: 4.66666666667
$e = (int) 9.9 - 1; D: 137.25
echo "E: $e\n"; D2: 137.25
$f = "sam" + 25; E: 8
echo "F: $f\n";
F: 25
$g = "sam" . 25;
echo "G: $g\n";
G: sam25
PHP vs. Python
$x = "100" + 25; x = int("100") + 25
echo "X: $x\n"; print "X:", x
$y = "100" . 25; y = "100" + str(25)
echo "Y: $y\n"; print "Y:", y
$z = "sam" + 25; z = int("sam") + 25
echo "Z: $z\n"; print "Z:", z

X: 125 X: 125
Y: 10025 Y: 10025
Z: 25 Traceback:"cast.py", line 5
z = int("sam") + 25;
ValueError: invalid literal
Control Structures
PHP Control Structures
Again, these are similar to those in C++ / Java
•if, while, do, for, switch are virtually identical to those in C++ and
Java
•PHP allows for an alternative syntax to designate a block in the if,
while, for and switch statements
Open the block with : rather than {
Close the block with endif, endwhile, endfor, endswitch
>Advantage to this syntax is readability
>Now instead of seeing a number of close braces, we see
different keywords to close different types of control structures
Conditional - if
• Logical operators ( == != < > <= >= && || ! )
• Curly braces

<?php
$ans = 42;
if ( $ans == 42 ) {
print "Hello world!\n";
} else {
print "Wrong answer\n"; Hello World!
}
?>
Multi-way x<2
yes
print 'Small'

$x = 7; no
yes
if ( $x < 2 ) {
x<10 print 'Medium'
print "Small\n";
} elseif ( $x < 10 ) { no
print "Medium\n";
} else { print 'LARGE'
print "LARGE\n";
}

print "All done\n";


print 'All Done'
Curly Braces are Not Required
if ($page == "Home") echo "You selected Home";
elseif ($page == "About") echo "You selected About";
elseif ($page == "News") echo "You selected News";
elseif ($page == "Login") echo "You selected Login";
elseif ($page == "Links") echo "You selected Links";

if ($page == "Home") { echo "You selected Home"; }


elseif ($page == "About") { echo "You selected About"; }
elseif ($page == "News") { echo "You selected News"; }
elseif ($page == "Login") { echo "You selected Login"; }
elseif ($page == "Links") { echo "You selected Links"; }
PHP Loop
Loops are used to execute the same block of code again and again, as long as
a certain condition is true.
In PHP, we have the following loop types:
•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
T
$fuel = 10;
while ($fuel > 1) {
print "Vroom vroom\n";
}

A while loop is a “zero-trip”


loop with the test at the top $fuel = 10;
while ($fuel > 1) {
before the first iteration starts.
print "Vroom vroom\n";
We hand construct the
$fuel = $fuel - 1;
iteration variable to
}
implement a counted loop.
$count = 1;
do {
echo "$count times 5 is " . $count * 5;
echo "\n";
} while (++$count <= 5);

A do-while loop is a “one-trip” 1 times 5 is 5


loop with the test at the 2 times 5 is 10
bottom after the first iteration 3 times 5 is 15
completes. 4 times 5 is 20
5 times 5 is 25
for($count=1; $count<=6; $count++ ) {
echo "$count times 6 is " . $count * 6;
echo "\n";
} 1 times 6 is 6
2 times 6 is 12
3 times 6 is 18
A for loop is the simplest way 4 times 6 is 24
to construct a counted loop. 5 times 6 is 30
6 times 6 is 36
Loop runs while TRUE (top-test)
Before loop starts Run after each iteration.

for($count=1; $count<=6; $count++ ) {


echo "$count times 6 is " . $count * 6;
echo "\n";
} 1 times 6 is 6
2 times 6 is 12
3 times 6 is 18
A for loop is the simplest way 4 times 6 is 24
to construct a counted loop. 5 times 6 is 30
6 times 6 is 36
Breaking Out of a Loop
• The break statement ends the current loop and jumps to the statement
immediately following the loop.

• It is like a loop test that can happen anywhere in the body of the loop.
for($count=1; $count<=600; $count++ ) { Count: 1
if ( $count == 5 ) break; Count: 2
echo "Count: $count\n"; Count: 3
} Count: 4
echo "Done\n"; Done
Finishing an Iteration with continue
The continue statement ends the current iteration. jumps to the top of
the loop, and starts the next iteration.

Count: 1
for($count=1; $count<=10; $count++ ) { Count: 3
if ( ($count % 2) == 0 ) continue; Count: 5
echo "Count: $count\n"; Count: 7
} Count: 9
echo "Done\n"; Done
PHP Functions
35
PHP Functions
36

(.) It is used to
concatenate
(join together)
two strings.
PHP Arrays
37

 An array is used to store multiple values, generally of same type, in a


single variable.
 we can traverse all the values stored in the array using for and
foreach loop.
 Index number for array elements starts from 0
Traversing PHP Indexed Array
38
PHP Array Functions
39

 sizeof($arr); = count($arr);
 is_array($arr) ? 'Array' : 'not an Array';
 in_array($var, $arr) ? 'Added' : 'Not yet! ';
 print_r($arr); //like foreach (But separated objects)
 array_merge($arr1, $arr2);
 array_push($arr, $val);
 array_pop($arr); //Removes the last item in array
 array_shift($arr); //Removes the first item in array
 sort($arr); // string value array, values are sorted in
ascending alphabetical order.
PHP String Functions
40

 strlen($str);
 str_word_count($str);
 strpos($str, $text);
 str_replace($replacethis, $replacewith, $str);
 str_repeat($str, $counter); //repeat some str no. of times
 substr($str, $start_pos, $length);// length of substring
 explode(separator, $str);// break a string
 implode(separator, $arr)// join string using separator.
Examples about PHP functions
41
Function with two arguments example
42
Arrays
An array in PHP is actually an ordered map.
A map is a type that associates values to keys.

array( key => value , ... )

// key may only be an integer or string


// value may be any value of any type
PHP Arrays
Creating Arrays
PHP Arrays can be created in a number of ways
Explicitly using the array() construct
Implicitly by indexing a variable
Since PHP has dynamic typing, you cannot identify a variable as an
array except by assigning an actual array to it
If the variable is already set to a string, indexing will have undesirable
results – indexes the string!
However, we can unset() it and then index it
We can test a variable to see if it is set (isset() and if it is an array
(is_array()) among other things
Lesson: Be careful with implicit behaviors
Size will increase dynamically as needed
More on PHP Arrays

Accessing Arrays – can be done in many ways


We can use direct access to obtain a desired item
Good if we are using the array as a hash table or if we need direct access for some other
reason
We provide the key and retrieve the value
For sequential access, the foreach loop was designed to work with arrays
Iterates through the items in two different ways
foreach ($arrayvar as $key => $value)
Gives both the key and value at each iteration
foreach ($arrayvar as $value)
Gives just the next value at each iteration
PHP Arrays
How can these both be done efficiently?
• PHP arrays are not implemented in the traditional way
Ex: In Java or C++ the array is a contiguous collection of memory
locations
• PHP arrays more resemble a linked list
But wouldn't this not allow direct access?
• The locations are also hashed
The "key" in PHP arrays is actually a hash value
• So sequential access follows the linked list
• Direct access accesses via the hash value
Creating & printing Arrays
// Create a simple array.
$array = array(1, 2, 3, 4, 5);
print_r($array);

Output: Array (
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
)
Creating & printing Arrays
// Create an array with forced indices.
$array = array(1, 1, 1, 1, 1, 8 => 1, 4 => 1, 19, 3 => 13);
print_r($array);
Array (
Output: [0] => 1
[1] => 1
[2] => 1
[3] => 13
[4] => 1
[8] => 1
[9] => 19
)
Foreach loop on Array
The most common use of the foreach loop, is to loop through the items of an array.

You might also like