0% found this document useful (0 votes)
6 views67 pages

Class 07-PHP Basics - Student

The document covers the basics of PHP, including variables, comments, operators, loops, and arrays. It explains how to write and run PHP code, use echo for output, and implement control structures like if statements and loops. Additionally, it introduces arrays and their indexing in PHP, along with examples and problems for practice.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views67 pages

Class 07-PHP Basics - Student

The document covers the basics of PHP, including variables, comments, operators, loops, and arrays. It explains how to write and run PHP code, use echo for output, and implement control structures like if statements and loops. Additionally, it introduces arrays and their indexing in PHP, along with examples and problems for practice.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 67

Class 07

CIS 245

PHP Basics
Learning Objectives
• PHP basics
– Variables- number and text
– Comments- line and block
– Arithmetic and logical operators
• Loops in PHP
– while, do..while, and for
– break and continue
• Arrays

2
Section 1

PHP BASICS

3
Introduction
• PHP is the language that you use to work on the server-side
Web page code:
– generate dynamic output—output that is potentially different each
time a browser requests a page.
– More secure than the client-side code
• PHP documents end with the extension .php
• Any HTML that has any PHP code must end with .php

4
PHP code markers
PHP code starts with <?php
It ends with ?>
We invoke PHP within HTML as follows
<?php
//php code goes here
?>

5
Review Question
• What is the purpose of PHP language? How is the PHP code
enclosed (tags) within HTML?

6
Running the PHP code
• XAMPP check
– Start XAMPP control panel from Start menu
– Start the Apache server
– Open browser with address https://localhost
– The following page will be displayed: http://localhost/dashboard/
• Preparing folder for PHP programs
– Locate where you installed XAMPP (c:\XAMPP will be the default)
– Go to the folder C:\xampp\htdocs
– Create a folder called cis245
– Place all your PHP programs here

7
Simple PHP code
Class06.php
<html>
<header>
<title>My first PHP program</title>
<body>
<?php
echo "My first PHP code";
?>
</body>
</html>

NOTE

Place this program at: C:\xampp\htdocs\cis245

To list all the programs in this folder on the


browser type: localhost/cis245

8
Comments in PHP
Two ways to add comments (similar to C++) <html>
<header>
• Line comment <title>My first PHP program</title>
<body>
starts with // <?php
Ex: //this is a line comment /*
This is the first PHP
• Block comment program to test XAMPP
starts with /* and ends with */ */
//echo writes content as HTML
Ex: /* echo "My first PHP code";
?>
This is a multiline or block </body>

comment </html>

*/

9
Basic syntax for PHP
• All statements end with a semicolon
• All variables begin with a $
• There are no explicit type declarations, similar to JavaScript
(example there are no int, string, etc.)
• Example
$x=19; //$x is assumed as type number
$y=“Hello”; //$y is assumed as type string

10
Variable assignment
• Variable can be assigned to other variables by an = sign
$x=10; //$x is assigned a value 10
$y=$x; //$x is assigned to $y
• Now $x and $y are having the same value, 10
• echo can be used to display content (HTML) on the browser

11
Review Question
• What is a variable? How are number and string variables
defined in PHP?

12
Example 1- Using echo

13
echo
• It puts all contents, following it, as a HTML
• Multiple lines within quotes can be used
• Variables can be used within the quotes
• echo <<<_END and _END can be used instead of quotes after
echo

14
Using echo for concatenation
There are two ways to concatenate the strings: single quote ’ ’,
and double quote “ ”
• Single quote does not evaluate the variables within the quote
• Double quote evaluates any variables that are present in the
quote.
Example. Let $x=8
• echo ‘$x’ prints $x; whereas echo “$x” prints 8

15
echo example(“ ”, ‘ ‘)
<?php <?php
$author = "Steve Ballmer"; $author = "Steve Ballmer";
echo “Developers! - $author.”; echo ‘Developers! - $author.’;
?> ?>

OUTPUT OUTPUT
Developers! – Steve Ballmer. Developers! – $author.

16
echo example (‘ ’)
<?php
$author = "Steve Ballmer";
echo ‘Developers! - $author.’;
?>

17
echo examples (_END)
<?php
$author = "Steve Ballmer";
// the last _END must not have spaces on either sides
echo <<<_END
Developers, Developers, developers, developers, developers,
developers, developers, developers, developers!
- $author.;
_END;
?>

18
Review Question
• What is the difference between double (") and single (') quote
when used in echo?

19
Operators- arithmetic
Operator Description Example
+ Addition $j + 1
- Subtraction $j - 6
* Multiplication $j * 11
/ Division $j / 4
% Modulus (remainder) $j % 9
++ Increment ++$j
-- Decrement --$j
20
Example 2- arithmetic operations

21
Problem 1
• Write a PHP code to define two variables $a=10 and $b=3.
Write code that will output the following.
OUTPUT <?php
$a=10; $b=3;
a*b = 30 $c=$a*$b;
a/b = 3.3333333333333 $d=$a/$b;
a/b = 3.33 $e=$a-$b;
a-b = 7 $f=$a+$b;
a+b = 13 echo "a*b = $c"."<br>";
echo "a/b = $d"."<br>";

$dr=number_format($d,2,'.','');
echo "a-b = $e"."<br>";
echo "a+b = $f";
?> 22
Operators- logical
Operator Description Example

&& And $j == 3 && $k == 2


and Low-precedence and $j == 3 and $k == 2
|| Or $j < 5 || $j > 10
or Low-precedence or $j < 5 or $j > 10
! Not ! ($j == $k)

== Check equality $j == 3
23
Checking TRUE [1] or FALSE [null]
• We can use the if statement to test if a logical operation (or, ||,
and, &&, !, <, >, ==) is true or false
• Other logical operators (called boolean) are
< less than > greater than
== equal to
• A true value is evaluated to 1, whereas a false value is
evaluated to null (or blank)

24
Review Question
• What is a Boolean value? In PHP, what is the value of a) true
and b) false

25
Example 3- logical operators
• Code

• Output

26
Checking true or false: if statement
• An if statement can be used to check if a logical operation is
true or false
• Format for the if statement is [else/elseif are optional]
• if (check condition) {..;..;}
elseif (condition) {..;..;}
elseif (condition) {..;..;}
else {..;..;}

27
if..elseif…else example
<?php
$page="News";
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";
else echo "You selected something different";
?>

OUTPUT
You selected News

28
Problem 2
• Write a PHP code to define two variables $a=10 and $b=3.
Write a code to check with individual if statements, whether
a>b, a<b, a>=b, b<=a, and a==b. Your code must output the
following. (do not use else/elseif)
• OUTPUT
10 is greater than 3
10 is greater than or equal to 3

29
Problem 2 Solution
<?php
$a=10; $b=3; //define variables
if($a>$b){
echo "<br>$a is greater than $b";
}
if($a<$b){
echo "<br>$a is less than $b";
}
if($a>=$b){
echo "<br>$a is greater than or equal to $b";
}
if($a<=$b){
echo "<br>$a is less than or equal to $b";
}
if($a==$b){
echo "<br>$a is greater than $b";
}
?>

30
Problem 2a
• Search the web and find how to find the remainder when $a is
divided by $b. Write a PHP code to find the remainder when $a
is divided by $b, where $a=5 and $b=2.

31
SECTION 2

LOOPS IN PHP

32
Loops in PHP
Loops run part of a code repeatedly
There are three types of loops
• while loop // loops only when condition is met
– while (condition is true){}
• do .. while loop // loops at least once then checks condition
– do{..} while (condition is true)
• for loop // loops only if condition is met (like while
loop)
– for(initialize, condition, modify){}

33
Example 4- Using while loop
print numbers 1 to 10
<?php
$count=1; //initialize count variable
to 1
echo "<br>";
while($count<=10){ //check if count <= 10, then
loop
echo "$count"." "; //dot is used to concatenate
strings
$count++; //increment count by 1
}
?>
34
Example 5- Using do .. while loop
print numbers 1 to 10
<?php
$count=1; //initialize count variable to
1
echo "<br>";
do{
echo "$count"." ";
$count++; //increment count by 1
}while($count<=10) //check if count <= 10, then
loop
?>
Output
1 2 3 4 5 6 7 8 9 10 35
Example 6- Using for loop
print numbers 1 to 10
<?php
echo "<br>";
// variable count is defined, initialized and
incremented
// within for loop
for($count=1;$count<=10; $count++){
echo "$count"." ";
}
?>
Output
1 2 3 4 5 6 7 8 9 10
36
Loops: break and continue
A break or a continue can be used to change the logic within the loop
• break breaks out of the inner loop
• continue skips the code following it and
continues with the next loop
Examples
• If ($x>10) break; //break loop if $x>10
• If ($x%2==1) continue; //skip to next loop count if remainder
1

37
Problem 3- Even numbers
Using continue/break
Write a code to print all even numbers between 1 and 20.
Note that you need to check if a number is divisible by 2 to know
if it is even. (ex: 4%2=0; 5%2=1 (remainder))
A. Use while loop
B. Use do .. while loop
C. Use for loop

38
Problem 3- Solution using for loop
<?php
echo "<br>Using continue in for loop to print even
numbers<br>";
//for loop; uses count variable to loop 10 times
for($count=1;$count<=10; $count++){
if ($count%2!=0) //check if count is odd- not divisible
by 2
continue; //go to next loop, skipping the
echo
echo "$count"." ";
}
?>
39
Problem 4- Odd numbers
Using continue/break
Write a code to print all odd numbers between 1 and 20.
Note that you need to check if a number is divisible by 2 to know
if it is even. (ex: 4%2=0; 5%2=1 (remainder))
A. Use while loop
B. Use do .. while loop
C. Use for loop

40
Problem 5- Stopping the Loop
Using continue/break
Write a code to print numbers between 1 and 20. Stop the loop
when the number is divisible by 8.
Note: if a number is divisible by X, then the remainder when it
divides a number is 0 (ex: 4%X=0; means X divides 4)
A. Use while loop
B. Use do .. while loop
C. Use for loop

41
Problem 5- Solution using for loop
Using continue/break
<?php
echo "<br>Using break in for loop to print until a
number is divisible by 8<br>";
// variable count is defined, initialised and
incremented
// within loop
for($count=1;$count<=20; $count++){
if ($count%8==0)
break;
echo "$count"." ";
}
?> 42
Problem 6- Fibonacci numbers
Write a code to print all 10 Fibonacci numbers. Fibonacci
numbers follow the formula: F(n)=F(n-1)+F(n-2), where F(0)=1,
and F(1)=1.
Use any loop you prefer.

Output:
1 1 2 3 5 8 13 21 34 55

43
Summary – PHP basics and Loops
• PHP is a language used to generate dynamic web pages
• PHP code starts with <?php and ends with ?>
• PHP has line comment starts with // and block comments within /* and */
• PHP has only two types of variables: number and string
• echo is used to output HTML code from PHP
• +, -, /, *, %, are arithmetic operators and ||, &&, ! are logical operators
• <, >, ==, <=.>=, <> are boolean operators
• TRUE=1 and FALSE= null (or empty string)
• Syntax for if: if(condition){} elseif(condition){}...else {}
• Loops in PHP are: while(){}, do{}while(), and for(){}

44
SECTION 3

ARRAYS IN PHP

45
Arrays
• Array stores a set of elements sequentially
• Each element must be indexed by unique numbers or strings
• Each array element is indexed, with the first element index
being zero (default, if index not used)
• Each array element can also be indexed by unique strings (user
defined index)
• PHP arrays can easily be sorted using predefined functions
(sort, asort, ksort, rsort, arsort, krsort)
46
PHP Arrays in RAM (memory)
Default Index User Defined Index

47
Review Question
• What is an Array in PHP? How does a default index array differ
from a defined index array?

48
Arrays using default index
$days=array(‘Monday’, ‘Tuesday’, ‘Wednesday’, ‘Thursday’,
‘Friday’, ‘Saturday’, ‘Sunday’);
In this case the default index is 0,1,2,3,4,5,6
Note that $days[0] refers to first element, and $days[6] refers to
the last element in the $days array.
Examples:
echo $days[0]; //prints Monday: index=0, value=Monday
echo $days[6]; //prints Sunday
49
Printing an array- using for loop
Not preferred for arrays
<?php
echo "<br>Printing array using for loop<br>";
//variable count is defined, initialised and incremented within
loop
$days=array('Monday', 'Tuesday', 'Wednesday', 'Thursday',
'Friday’, 'Saturday', 'Sunday');
for($index=0;$index<=6; $index++){
echo "$index>"."$days[$index]; ";
}
?>

OUTPUT
Printing array using for loop
0->Monday; 1->Tuesday; 2->Wednesday; 3->Thursday; 4->Friday; 5->Saturday; 6->Sunday;
50
Printing an array- using foreach
Designed for arrays
• foreach($array_name as $index=>$value)
– where $index is the array index and $value its corresponding value
<?php
echo "<br>Using default array<br>";
//variable count is defined, initialised and incremented within loop
$days=array('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday',
'Saturday’, 'Sunday');
foreach($days as $index=>$value){
echo "$index->"."$value; ";
}
?>
Using default array
0->Monday; 1->Tuesday; 2->Wednesday; 3->Thursday; 4->Friday; 5->Saturday; 6->Sunday;

51
Array with a defined index
• Some time default index 0,1,etc., may not correspond with the
values in a meaningful way.
• For example, in the array $days, there is no real relation
between key=0 and value=Monday
• It is sometimes useful to define our own key that is meaningful
and helps identify the value
– For example key=“Mon” can easily relate to value=“Monday”

52
Declaring arrays with own index
• We can also define our own indices for the array elements as
follows: index=> element

• $days=array(‘Mon’=>'Monday', ‘Tue’=> 'Tuesday',


‘Wed’=> 'Wednesday', ‘Thu’=> 'Thursday', ‘Fri’=>
'Friday', ‘Sat’=> 'Saturday’,‘Sun’=> 'Sunday’);

• $days[‘Mon’] refers to the first element

53
Example
Days of the week using defined index
<?php
echo "<br>Using defined index<br>";
//variable count is defined, initialised and incremented within
loop
$days=array('Mon'=>'Monday', 'Tue'=>'Tuesday', 'Wed'=>'Wednesday’,
'Thu'=>'Thursday', 'Fri'=>'Friday',
'Sat'=>'Saturday’, 'Sun'=>'Sunday');
foreach($days as $index=>$value){
echo "$index->"."$value; ";
}
?>
OUTPUT
Using defined index
Mon->Monday; Tue->Tuesday; Wed->Wednesday; Thu->Thursday; Fri->Friday; Sat->Saturday; Sun->Sunday;
54
Problem
• Define two arrays PROD_ID PROD_NAME PROD_COST
AB01 Chicken Sticks 7.89
prod_name and SD02 Pizza 12.99
prod_cost whose index BD05 Lasagna 8.65
XP99 Fries 3.49
is pro_id. MS54 Burgers 5.55
PR98 Nuggets 2.49
• Print both these arrays ED12 Fried Rice 9.99
using foreach loop as
shown in the previous
examples

55
Sorting Arrays
• There are three sort functions: sort(), asort(), and ksort().
• asort() is useful as it sorts by value keeping the key-value link
1. sort($array_name)
– Sorts by increasing value discarding the key order
2. asort($array_name)
– Sorts by increasing value retaining the key-value link
3. ksort($array_name)
– Sorts by increasing key retaining key-value link

56
Review Question
• Name and explain one sorting function in PHP that will
preserve key-value link

57
Problem: using asort()
use $prod_name array
asort will sort by the value, and keep the key->value connection

1. Use the $prod_name array you defined previously and store it


a new array called $prod_name_asort
2. Use asort() to sort the new array $prod_name_asort
3. Print this sorted array using foreach

58
Problem: using ksort()
use $prod_name array
ksort will sort by the key, and keep the key->value connection

1. Use the $prod_name array you defined previously and store it


a new array called $prod_name_ksort
2. Use ksort() to sort the new array $prod_name_ksort
3. Print this sorted array using foreach

59
Problem: using asort()
use $prod_cost array
asort will sort by the value, and keep the key->value connection

1. Use the $prod_cost array you defined previously and store it a


new array called $prod_cost_asort
2. Use asort() to sort the new array $prod_cost_asort
3. Print this sorted array using foreach

60
Problem: using ksort()
use $prod_cost array
ksort will sort by the key, and keep the key->value connection

1. Use the $prod_cost array you defined previously and store it a


new array called $prod_cost_ksort
2. Use ksort() to sort the new array $prod_cost_ksort
3. Print this sorted array using foreach

61
Sorting by decreasing/reverse order
There are three reverse sort functions
• rsort() //compares with sort()
– Sorts by decreasing value discarding the key order
• arsort() //compares with asort()
– Sorts by decreasing value retaining the key-value link
• krsort() //compares with ksort()
– Sorts by decreasing key retaining key-value link

62
Review Question
• Name and explain one reverse sorting function in PHP that will
preserve key-value link

63
Problem: using arsort()
use $prod_name array
arsort will reverse sort by the value, and keep the key->value
connection

1. Use the $prod_name array you defined previously and store it


a new array called $prod_name_arsort
2. Use arsort() to sort the new array $prod_name_arsort
3. Print this sorted array using foreach

64
Problem: using krsort()
use $prod_name array
krsort will reverse sort by the key, and keep the key->value
connection

1. Use the $prod_name array you defined previously and store it


a new array called $prod_name_krsort
2. Use krsort() to sort the new array $prod_name_krsort
3. Print this sorted array using foreach

65
Problem: using arsort()
use $prod_cost array
arsort will reverse sort by the value, and keep the key->value
connection

1. Use the $prod_cost array you defined previously and store it a


new array called $prod_cost_arsort
2. Use arsort() to sort the new array $prod_cost_arsort
3. Print this sorted array using foreach

66
Problem: using krsort()
use $prod_cost array
krsort will reverse sort by the key, and keep the key->value
connection

1. Use the $prod_cost array you defined previously and store it a


new array called $prod_cost_krsort
2. Use krsort() to sort the new array $prod_cost_krsort
3. Print this sorted array using foreach

67

You might also like