0% found this document useful (0 votes)
25 views30 pages

Lecture Silde 25-54

PHP

Uploaded by

suppershort135
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views30 pages

Lecture Silde 25-54

PHP

Uploaded by

suppershort135
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

PHP

Syntax: Conditional and Looping Statements


Conditional Statements
In PHP we have the following conditional statements:

• if statement - executes some code if one condition


is true
• if...else statement - executes some code if a
condition is true and another code if that condition is
false
• if...elseif...else statement - executes different codes
for more than two conditions
• switch statement - selects one of many blocks of
code to be executed
Conditional Statements
if (condition / boolean expression)
{statements Example:
//code to be executed if this condition is true;
<?php
}
$t = date("H");
else if (another condition)
{ statements
if ($t < "10") {
//code to be executed if first echo "Have a good
condition is false and this morning!";
condition is true; } elseif ($t < "20") {
// there may be more than one else if echo "Have a good day!";
block } else {
} echo "Have a good
else {statements night!";
//code to be executed if all conditions are false; }
} ?>
The while loop
while (condition) {
statements
}

$x = 2;
while ($x < 1000) {
echo $x . “n”; // \n is newline character
$x = $x * $x;
}
Value of $x $x < 1000? Result
2 TRUE prints 2
4 TRUE prints 4
16 TRUE prints 16
256 TRUE prints 256
65536 FALSE exits loop
The do-while loop
 The code within the loop is executed at least once,
regardless of whether the condition is true
do {
statements
} while (condition);

equivalent to:

statements
while (condition) {
statements
}
The for loop
for (init; condition; increment) {
statements
}
equivalent to:
init
while (condition) {
statements
increment
}

Prints the first 10 positive integersand their


squares:

for ($i = 1; $i <= 10; $i++) {


echo $i . “:” . ($i * $i) . “\n”;
}
PHP
Syntax: Functions and Global Variables
Defining your own functions
function function_name ($arg1, $arg2) {
function code function parameters
return $var // optional
}

Example: a simple multiply function


function multiply($x, $y) {
echo $x * $y;
echo “\n”;}
multiply(5, 1.2);  prints 6
$a = 5;
$b = 1.2;
multiply($a, $b);  prints 6
$a = array(1,2,3);
multiply($a, $b);  error
$a = “string”
multiply($a, $b);  prints 0 (?!)
Return values
 A function can return a value after it is done
 Usethis value in future computation, uselike a variable,
assign value to a variable
 A modified multiply function
function multiply($x, $y) {
return $x * $y;
}
multiply(2,3);  prints nothing! returns value, but we don’t store anywhere
echo multiply(2,3);  prints 6
$a = multiply(2,3);  assignsthe value 6 to the variable $a
$b = multiply(multiply(2,3), multiply(3,4));  assignsthe value
72 to the variable $b
Return values
 A function can return at most once, and it can only return one
value
 If it does not return anything, assignments will result in NULL
 A function ends after it returns, even if there is code following
the return statement
function do_stuff($x) {
if ($x % 2 == 0) { // if even
return $x/2 // exits function at this point
}
// this is ONLY executed if x is odd
$x += 5;
if ($x < 10) {
$x += 3;
}
return x;
}
Making function calls
 Code inside of a function is not executed unless the function is
called.
 Code outside of functions is executed whenever the program is
executed.
<?php
… // some code
function1(); // makes function call to function1(), which
// in turn calls function3()

function function1() {
… // some code
function3(); // makes function call to function3()
}
function function2() { // this function is never called!
… // some code
}
function function3() {
… // some code
}
?>
Variable scope
 Variables declared within a function have local scope
 Can only be accessed from within the function
<?php
function function1() {
… // some code
$local_var = 5; // this variable is LOCAL to
// function1()
echo $local_var + 3; // prints 8
}

… // some code
function1();
echo $local_var; // does nothing, since $local_var is
// out of scope

?>
Global variable scope
 Variables declared outside a function have global
scope
 Must use global keyword to gain access within functions
<?php
function function1() {
echo $a; // does nothing, $a is out of scope
global $a; // gain access to $a within function
echo $a; // prints 4
}

… // some code
$a = 4; // $a is a global variable
function1();

?>
PHP
Syntax: Arrays
Arrays as a list of elements
 Use arrays to keep track of a list of elements using
the same variable name, identifying each element by
its index, starting with 0
$colors = array(‘red’, ‘blue’, ‘green’, ‘black’, ‘yellow’);

 To add an element to the array:


$colors[] = ‘purple’;

 To remove an element from the array: Print using echo:


$arrlength =
unset($colors[2]); count($colors);
 To print elements of the array: for($x = 0; $x <
$arrlength; $x++) {
$colors = array_values($colors); echo $colors[$x];
print_r($colors); echo "<br>";
}
Arrays as key-value mappings
 Use arrays to keep track of a set of unique keys and the
values that they map to – called an associative array
$favorite_colors = array(‘Joe’ => ‘blue’, ‘Elena’ => ‘green’,
‘Mark’ => ‘brown’, ‘Adrian’ => ‘black’, ‘Charles’ => ‘red’);

 To add an element to the array:


$favorite_colors[‘Bob’] = ‘purple’;
 To remove an element from the array:
unset($favorite_colors[‘Charles’]);
 Keys must be unique:
$favorite_colors[‘Joe’] = ‘purple’ overwrites ‘blue’
PHP
More about arrays and the for-each loop
All arrays are associative
 Associative arrays are arrays that use named keys that you
assign to them.
 Take our example of a list:
$colors = array(‘red’, ‘blue’, ‘green’, ‘black’, ‘yellow’);

 print_r($colors) gives:
Array(
[0] => red
[1] => blue
[2] => green
[3] => black
[4] => yellow
)
 Turns out all arrays in PHP are associative arrays
🞑 In the example above, keys were simply the index into the list
 Each element in an array will have a unique key, whether you
specify it or not.
Specifying the key/index
 Thus, we can add to a list of elements with any
arbitrary index
🞑 Usingan index that already existswill overwrite the
value
$colors = array(‘red’, ‘blue’, ‘green’, ‘black’, ‘yellow’);
$colors[5] = ‘gray’; // the next element is gray
$colors[8] = ‘pink’;// not the next index, works anyways
$colors[7] = ‘orange’ // out of order works as well
Array functions
 isset($array_name[$key_value]) tells whether a variable
is set, which means that it has to be declared and is not NULL.
 unset($array_name[$key_value]) removes the key-value
mapping associated with $key_value in the array
🞑 The unset() function does not “re-index” and will leave

gaps in the indices of a list of elements since it simply


removes the key-value pairing without touching any other
elements
 array_keys($array_name) and
array_values($array_name) returns lists of the keys and
values of the array
Adding elements without specifying the
key
 Recall that we did not specify the key when adding to a
list of elements:
$colors = array('red', 'blue', 'green', 'black',
'yellow');
$colors[] = 'purple';
 PHP automatically takes the largest integer key that has ever
been in the array, and adds 1 to get the new key
$favorite_colors = array(“Joe” => “blue”, “Elena”
=> “green”, “Mark” => “brown”, “Adrian” =>
“black”, “Charles” => “red”);
$favorite_colors[] = 'new color 1'; // key is 0
$favorite_colors[7] = 'another new color';
$favorite_colors[] = 'yet another color'; // key is 8
unset($favorite_colors[8]);
$favorite_colors[] = 'color nine'; // key is 9, the old
// maximum is 8 even though it no longer exists!
The for-each loop
 The for-each loops allow for easy iteration over all
elements of an array.
foreach ($array_name as $value) {
code here
}
foreach ($array_name as $key => $value) {
code here
}

foreach ($colors as $color) {


echo $color; // simply prints each color
}
foreach ($colors as $number => color) {
echo “$number => $color”; // prints color with index
// to change an element:
// $colors[$number] = $new_color;}
isset() Function
 The isset() function checks whether a variable is set, which means
that it has to be declared and is not NULL.
 This function returns true if the variable exists and is not NULL,
otherwise it returns false.
Note: If multiple variables are supplied, then this function will return true
only if all of the variables are set.
 Example: Check whether a variable is empty. Also check
whether the variable is set/declared. Example for Array:
<?php $a = array ('test' => 1,
'hello' => NULL, 'pie' =>
$a = 0;// True because $a is set 3.1)
if (isset($a)) { If (isset($a['test'])
echo "Variable 'a' is set.<br>"; //True
{
}
Some code
$b = null; // False because $b is NULL }
if (isset($b)) { If (isset($a[‘hello'])
echo "Variable 'b' is set."; //false
{
}?> Some code}
PHP
HTTP Requests and Forms
Passing information to the server
 Sometimes, we require additional values be
passed from client to server
🞑 Login: username and password

🞑 Forminformation to be stored on server


 GET request: pass information via the URL
🞑 http://www.yourdomain.com/yourpage.php?firstparam
=firstvalue&secondparam=secondvalue or
🞑 localhost/yourpage.php?firstparam =firstvalue &
secondparam=secondvalue
🞑 Access values server-side using $_GET superglobal
 $_GET[‘firstparam’] => ‘firstvalue’
 $_GET[‘secondparam’] => ‘secondvalue’
Passing information to the server Example

 Client-side: <html> <head> <title> Passing Information </title>


</head>
<body>
<a href="ICE_dept.php?Uni_name=PUST &
Dept_name=ICE"> ICE Department</a>
</body> </html>
 Server-side: <html> <head> <title> Receiving Information</title>
</head>
<body>
<label> University Name: </label>
<?php echo $_GET['Uni_name']; ?>
<label> Department Name: </label>
<?php echo $_GET['Dept_name']; ?>
</body> </html>
When to use $_GET vs. $_POST
 GET requests are sent via the URL, and can thus
be cached, bookmarked, shared, etc
 GET requests are limited by the length of the URL
 POST requests are not exposed in the URL and
should be used for sensitive data
 There is no limit to the amount of information
passed via POST
Dealing with forms
 Forms are generally used to collect data, whether the
data needs to be stored on the server (registration) or
checked against the server (login)
 2 components to a form:
🞑The HTML generating the form itself
🞑The server-side script that the form data is sent to
(via GET or POST), taking care of the processing
involved
 Server should respond appropriately, redirecting
the user to the appropriate destination or
generating the appropriate page
Forms: client-side
<html>
<head>
<title> A Form Example </title>
</head><body>
<form action="welcome.php" method="post">
Name: <br /> <input type="text" name="name" /><br />
Phone Number: <br /> <input type="text" name="phone" /><br />
<input type="submit" value="Submit">
</form>
</body>
</html>

 form action – where to send the form data


 method – how to send the data (GET or POST)
 Name attributes become the keysusedto accessthe
corresponding fields in the $_GET or $_POST arrays
Forms: server-side

<html>
<head><title>This is welcome.php</title></head>
<body>
The name that was submitted was: &nbsp;
<?php echo $_POST['name']; ?><br />
The phone number that was submitted was: &nbsp;
<?php echo $_POST['phone']; ?><br />
</body>
</html>

 A simple PHP file that displays what was entered


into the form
🞑 Can do many other things server-side depending on the
situation
 Note the use of $_POST

You might also like