You are on page 1of 76

Client Side Scripting &

Flow Control Functions


in PHP
-The Building Blocks of PHP
-Flow Control Functions in PHP

3.1Variables
3.2Data Types
3.3Operators and Expressions
3.4Constants
3.5Switching Flow
3.6Loops
3.7Code Blocks and Browser Output
3.8JavaScript
3.9Implementing JavaScript in PHP codes
3.10Summary

WHAT YOU WILL LEARN


About variable what they are, why need to use them,
and how to use them
How to define and access variables
About data types
About some of the more commonly used operators
How to use operators to create expressions
How to define and use constants

CONT
How to use the if statement to execute code if a test expression evaluates to
true.
How to execute alternative blocks of code when the test expression of an if
statement evaluates to false.
How to use the switch statement to execute code based on the value
returned by a test expression.
How to repeat execution of code using a while statement.
How to use for statements to make neater loops.
How to break out of loops.
How to nest one loop within another.

How to use PHP start and t

3.1 VARIABLE

3.1
VARIABLE
VARIABLE is a special container that you can define,
which will then 'hold' a value such as a number, string,
object, array or Boolean.
consist of a name of your choosing, precedes by a dollar
sign($)
- name should meaningful
- can include numbers,letters and underscore( _ ).
- must beging with a letter or an underscore ( _ ).
-cannot space
EXAMPLE: $a ;
$2345;

3.1 CONT

Semicolon ( ; ) AKA instruction terminator used to end


a PHP statement
Declaring variable: assign a value to it in the same
statement.
EXAMPLE:$num1 = 8;
$num2 = 23;

3.1.1 LOCAL VARIABLES


A variable declared in a function is considered local; that is, it can be
referenced solely in that function.
Any assignment outside of that function will be considered to be an
entirely different variable from the one contained in the function

3.1.2 GLOBAL VARIABLES


A global variable can be accessed in any part of the program.
A global variable must be explicitly declared to be global in the function in which it is to
be modified.
Placing the keyword GLOBAL in front of the variable that should be recognized as global.
Placing this keyword in front of an already existing variable tells PHP to use the variable
having that name.

3.1.2 SUPERGLOBALS VARIABLES


Always present and their values available to all script.
Each of following superglobals is actually an array of other
variables:TYPE

DESCRIPTION

$_GET

contains any variables provided to a script through the GET method

$_POST

contains any variables provided to a script through the POST method

$_COOKIE

contains any variables provided to a script through a cookie

$_FILES

contains any variables provided to a script through file upload

$_SERVER

contains information such as headers, file paths, and script locations.

$_ENV

contains any variables provided to a script as part of the server


environment

$_REQUEST

contains any variables provided to a script via any user input


mechanism.

$_SESSION

contains any variables that are currently registered in a session.

3.2 DATA TYPE

3.2 DATA TYPE


Take up different amounts of memory and manipulated by
a script.
Variables can be used flexibly.
- The data type can be change

Standard data type


TYPE

EXAMPLE

DESCRIPTION

Boolean

True

Integer

Float or Double

3.234

A floating-point number

String

hello

A collection of characters

One of the special values true or false


A whole number

Object

An instance of a class

Array

An ordered set of keys and values

Special data type


Type
Resource
s
NULL

Description
References to a third-party resources (for
exampla : database)
An unintialized variable

TESTING VARIABLE TYPE


Test the validity of a particular type of variable with
function
- The is_* family functions (e.g. is_bool() ) test
whether a given value is Boolean.
NOTE: You can read more about calling
functions in Chapter 7.

TUTORIAL 3.2
TESTING THE TYPE OF A VARIABLE
<html>
<head>
<title>Tutorial 3.2 testing the type of vriable</title>
</head>
<body>
<?php
$testing;//declare without assigning
echo gettype($testing);//null
echo"<br>";
$testing = 5;
echo gettype($testing);//integer

echo"<br>";
$testing = "five";
echo gettype($testing);//string
echo"<br>";
$testing = 5.0;
echo gettype($testing);//double
echo"<br>";
$testing = true;
echo gettype($testing);//boolean
echo"<br>";
?>
</body>
</html

output 3.2

CHANGING TYPE WITH settype()


Function settype() to change the variable type.
//settype()

<?php
$undecided = 3.14;
echo is .$undecided. a double? .is_double($undecided).<br/>;
//double
settype($undecided, string);
echo is .$undecided. a string? .is_string($undecided).<br/>; //string
settype($undecided, integer);
echo is .$undecided. an integer? .is_integer($undecided).<br/>;
//integer
settype($undecided, double);
echo is .$undecided. a double? .is_double($undecided).<br/>;
//double
settype($undecided, bool);
echo is .$undecided. a boolean? .is_bool($undecided).<br/>;
//boolean
?>

output

changing type by casting


Produces a copy, leaving the original variable
untouched.
//bycasting.php
<?php
$undecided = 3.14;
$holder = (double) $undecided;
echo is .$holder. a double? .is_double($holder).<br/>; //double
$holder = (string) $undecided;
echo is .$holder. a string? .is_string($holder).<br/>; // string
$holder = (integer) $undecided;
echo is .$holder. an integer? .is_integer($holder).<br/>;
//integer
$holder = (double) $undecided;
echo is .$holder. a double? .is_double($holder).<br/>; //double
$holder = (boolean) $undecided;
echo is .$holder. a boolean? .is_bool($holder).<br/>; // boolean
echo <hr/>;
echo original variable type of $undecided: ;
echo gettype($undecided); // double
?>

output

3.3 OPERATORS &


EXPRESSION

3.3.1 OPERATORS
Symbol or series of symbols
An operand is a value used in conjunction with an
operand.
Example:
I.
II.
III.

(9 + 1)
9 and 1 is the operand
+ is the operator.

3.3.2 EXPRESSION
Any combination of functions, values and operators that
resolves to a value.
Example:

(9 + 1) = 10
10 is the expression.

3.3.3 ASSIGNMENT OPERATOR


Consist of single character
Takes value on the right-side and assign it to the leftside operand.
also is an expression.
Example:
$name = Nadia ;
$name is the variable
Nadia ; is the string

3.3.4 ARITHMETIC OPERATOR


Addition (+)
Subtraction (-)
Division (/) ,
Multiplication (*)
Modulus (%)

3.3.5 CONCATENATION OPERATOR


Single period (.) which returns concatenation of its right
and left arguments.
Example:
hello. world become hello world

3.3.6 COMBINED ASSIGNMENT


OPERATOR

Consists of a standard operator symbol followed by an equal sign.

a) +=
b) -=
c) *=
d) /=
e) %=
f) .=
Example:

$x = 5 ;
$x += 5 ; // $x now equals 10

3.3.7 INCREMENT AND DECREMENT


Use in counting the iterations of loop
Add or subtract integer constant 1 from an integer
variable
Known as post-increment and post-decrement.
Example:

i. $x++; // $x is incremented by 1
ii. $x--; // $x is decremented by 1

3.3.8 COMPARISONS OPERATORS


Perform comparative test using their operands
Return Boolean value( true , false )
Operators:1) Equivalence ==
2) Non-equivalence !=
3) Identical ===
4) Greater than >
5) Greater than or equal to >=
6)Less than <
7)Less than or equal to <=

3.3.9 LOGICAL OPERATORS


To test the combination of Boolean values
Operators:
1) || Or(left or right is true)
2) or Or(left or right is true)
3) xor Xor(left or right is true, but not both)
4) && And(left and right are true)
5) and And(left and right are true)
6) ! Not(the single operand is not true)

3.3.10 OPERATOR PRECEDENCE


PHP engine read an expressions from left to right ( within an expression)
Ex: (4 + 5) *2 by putting parentheses
In precedence order:
++, --, (cast)
/, *, %
+, <, <=, =>, >
==, ===, !=
&&
||
=, +=, -=, /=, *=, %=, .=
and
xor
or

low

3.4 CONSTANT

CONSTANT
To keep the value and the data type remain unchanged
throughout the scripts execution.
To defined a constants ;must use PHPs built in define() function.
It is subsequently cannot be change unless been specifically
define() again.
Name of the constant and the value must be place within the
parentheses() and separate in by a comma.
Example of using define():
define(THE_YEAR, 2015);
Value for a constants can be a number, a string or a Boolean.

CONT
Name of the constants must be in capital letters.
Constants can only be access by the constants name.
Constants can be used anywhere in the scripts, including the functions stored in
the external files.
Constant names are case sensitive.
The behavior can be change by passing true to the define() function
To set up THE_YEAR constant as define(THE_YEAR, 2015, true);
By putting true at the back of the define() constant, it can be access without
worrying about the case.
echo the_year;
echo ThE_YeAr;
echo THE_YEAR;

3.4.1 PREDEFINED CONSTANT


PHP automatically provides some built-in constants for us.

CONT

These magic constants are not statically predefined and


instead change depending on the context in which they are
used.
You can also find out which version of PHP is interpreting
the script with the PHP_VERSION constant.
This constant can be useful if you need version
information included in script output when sending a bug
report.

SWITCHING FLOW

IF STATEMENT
If statement use to control the execution of a statement
that follows it.
If the expression results in a true value, the statement
is executed. Otherwise, the statement is skipped
entirely.

TUTORIAL 3.5
//Tutorial 3.5
a)happy.php
<?php
$mood = happy;
if ($mood == happy) {
echo good for you boi ;
}
?>

OUTPUT

b) USING ELSE CLAUSE WITH THE IF


STATEMENT
The function of else is to evaluate the false statement. If
the first expression is false, then it will execute the second
expression.
Only two expressions are required in this statement.

TUTORIAL 3.5
//tutorial 3.5
b)hoorayww.php
<?php
$mood = sad;
if ($mood == happy) {
echo Hooray! Im in a good mood!;
} elseif ($mood == sad) {
echo Awww. Dont be down!;
} else {
echo Im neither happy nor sad, but
$mood.;
}
?>

OUTPUT

c) SWITCH STATEMENT
A switch statement evaluates only one expression in the
list. Selecting the correct one based on a specific bit of
matching code.
By using the if statement in conjunction with else if, the
program can evaluate multiple expressions.
The break statement is important. Without a break
statement, the program flow continues to the next case
statement and ultimately to the default statement.

TUTORIAL 3.5
//tutorial 3.5
c)neither.php
<?php
$mood = sad;
switch ($mood) {
case happy:
echo good for you boi;
break;
case sad:
echo well, Dont feel so down!;
break;
default:
echo Im neither happy nor sad, but $mood.;
break;
}
?>

OUTPUT

d) USING THE ?: OPERATOR


The ?: or ternary operator is similar to the if statement,
except that it returns a value derived from one of two
expressions separated by a colon.
eg. :
(expression) ? returned_if_expression_is_true :
returned_if_expression_is_false;
If the test expression evaluates to true, the result of the
second expression is returned; otherwise, the value of
the third expression is returned.

TUTORIAL 3.5
//tutorial 3.5
d)sad.php
<?php
$mood = sad;
$text = ($mood == happy) ? I
am in a good mood! : I am in a
$mood mood.;
echo $text;
?>

OUTPUT

LOOPS

LOOPS
Scripts can make and decide how many times to execute a block of
code.
Loop statement can perform repetitive tasks.
The task stops when you choose to exit loop.

WHILE... STATEMENT
Always executes if the
expression is true.
Execution is called an iteration.

OUTPUT

TUTORIAL
<?php
$counter = 1;
while ($counter <= 12) {
echo $counter. times 2 is .($counter
*2).<br />;
$counter++;
}
?>

DO... WHILE STATEMENT


The code block is executed before the truth test.
Always end with a semicolon (;).
Useful to execute once even it is false.
How to use :
do {
// code to be executed
} while (expression);

TUTORIAL

<?php
$num = 1;
do {
echo The number is: .
$num.<br />;
$num++;
} while (($num > 200) &&
($num <400));
?>

OUTPUT

CONT...
Output :
The number is: 1
If you change the value of $num in line 2 to 300 and then run the
script, the loop displays
The number is: 300
and continues to print similar lines, with increasing numbers, through
The number is: 399

FOR... STATEMENT
Same result as while statement but in one line of code.
Infinite loops run without bounds and giving stress to the web
server and also renders the web page unusable.
How to use :
for (initialization expression; test
expression) {
// code to be executed
}

expression; modification

TUTORIAL

OUTPUT
<?php
for ($counter=1;
$counter<=12; $counter+
+) {
echo $counter. times 2 is .
($counter * 2).<br />;
}
?>

BREAK STATEMENT
Can break loop based on the results of
additional rules and protect against
error.
PHP gives warning if been divided by 0
and continue the execution.

TUTORIAL:

<?php
$counter = -4;
for ( $counter <= 10; $counter++) {
if ($counter == 0) {
break;
} else {
$temp = 4000/$counter;
echo 4000 divided by .$counter.
is....$temp.<br/>;
}
}
?>

OUTPUT

CONTINUE STATEMENT
Used to skip iteration
Can end the iteration without the loop
being stopped and avoid a divide-by-0
error.
TUTORIAL
<?php
$counter = -4;
for (; $counter <= 10; $counter++) {
if ($counter == 0) {
continue;
}
$temp = 4000/$counter;
echo 4000 divided by .$counter. is....
$temp.<br />;
}
?>

OUTPUT

54/CODE BLOCKS &


BROWSER OUTPUT

CODE
BLOCK
&
BROWSER
OUTPUT
There is two ways to create within code blocks:
a.
b.

A code blocks containing multiple echo statement


Returning to HTML mode within a code block

Output of two next example tutorial based on code blocks:

a) A Code Blocks Containing Multiple Echo Statement


Example 3.7.1

oster = true;
tyRoster){
o <table border=\ 1\ >\n;
o <tr><td colspan=\ *5\>;
o <Duty Roster;
o </td></tr>;
<tr>
onday</td><td>Tuesday</td><td>Wednesday</td><td>Thursday</td><td>Friday</td>
;
o </table>;

TUTORIAL 3.7

yRoster = true;
if the value of $display_prices is set to true in this line, the table is printed.
DutyRoster){ for readability codes, output into multiple echo() statements

ho <table border=\ 1\ >\n;


ho <tr><td colspan=\ *5\>;
ho <Duty Roster;
ho </td></tr>;
ho<tr><td>\Monday</td><td>\Tuesday</td><td>\Wednesday</td>
d>\Wednesday</td><td>\Thrusday</td><td>\Friday</td></tr>\n;
ho </table>;

Tutorial 3.7
* Save it in the notepad, then set as .php format and saves into c://apache2//htdocs file. Use the browser (localhost/filename) to open the output.

b) Returning to HTML mode within a code blocks

Example 3.7.2

html><body> <?php
utyRoster= true;
$DutyRoster) {
In line 4, shift to HTML mode occurs only if the condition of if statement is fulfilled.
able border=1>
r><td colspan=5>Duty Roster</td></tr>
tr>
d>Monday</td>
d>Tuesday</td>
d>Wednesday</td>
d>Thrusday</td>
d>Friday</td>
tr>
table>
php
?>
body></html>

3.8 JAVASCRIPT

3.8 JAVASCRIPT
-JavaScript is a programming language
JavaScript isnotthe same as Java .
Designed as a browser, client-side scripting language for the Web,
supplementing HTML
Similar syntax to C, C++, and Java.
Interpreted, scripting language, not a full programming language.
Platform-independent.
-Both client-side (browser-based) JavaScript and server-side JavaScript. Most
focus is on the client
-JavaScript is a way to enhance WWW pages within a WWW browser
Example: Pop-ups windows, form verification, dynamic pages

3.9 IMPLEMENTATION
OF
JAVASCRIPT IN PHP

PHP codeis executed on the server side and output data are transmitted to
Web browser.
JavaScript script codeis executed by the browser on user's computer.
There are two ways to combine PHP with JavaScript to achieve a dynamic and
personalized result:
By writing the entire JS script within PHP code and adding it to the web
page with PHP function "echo" (or "print").
Example; <?php echo '<script type="text/javascript"> // JS code ... </script>'; ?>

By adding in the JS script within the HTML document only the necessary
data processed by PHP.
Example; <script type="text/javascript"> var var_js = <?php echo $var_php;?>;

EXAMPLE
1. Alert window with the user name
In a web site with authentication system to be
displayed an alert window with the user name, after
he logged in.
In this case we assume that the username is stored in
a session variable ($_SESSION['name']).

TUTORIAL
welcome(js_in_php).php
<?php
// ... php code ...
echo '<scripttype="text/javascript">alert("Welcome '. $_SESSION['name'].
'");</script>';
?>

OR
welcome(js_in_html).php
<?php session_start(); ?>
<!-- HTML code -->
<script type="text/javascript">alert("Welcome <?php echo $_SESSION['name']; ?
>");
</script>

CONT

OUTPUT

EXAMPLE

2. Clock with server time


A clock made with JavaScript and added in a web page
will display the visitor's computer time. If you want to
display the same time for all visitors, you can add and
use the server time in the JS script, as it is in the
following example:

TUTORIAL
ServerClock.php
<div id="tag_ora"></div>
<script type="text/javascript"><!
// Clock script server-time, http://coursesweb.net
// use php to get the server time
var serverdate = new Date(<?php echo date('y,n,j,G,i,s'); ?>);
var ore = serverdate.getHours(); // hour
var minute = serverdate.getMinutes(); // minutes
var secunde = serverdate.getSeconds(); // seconds
// function that process and display data
function ceas()
{ secunde++;
if (secunde>59) {
secunde = 0;
minute++;
}

CONT
if (minute>59) {
minute = 0;
ore++;
}
if (ore>23) {
ore = 0;
}
var output = "<font size='4'><b><font size='1'>Ora
server</font><br/>"+ore+":"+minute+":"+secunde+"</b></font>
document.getElementById("tag_ora").innerHTML = output;
}
// call the function when page is loaded and then at every second
window.onload = function(){
setInterval("ceas()", 1000);
}
--></script>

EXAMPLE

3. Displaying data from PHP with JavaScript,


according to a URL
Maybe you have seen in sites for traffic or banner that is
necessary to add a little JavaScript code in the page with
a specific "src" attribute.
They use the same principle, to combine PHP with
JavaScript.
The URL in the JS code added in the web page calls a PHP
script. The PHP script uses$_GETto get the parameters
from the received URL. According to those parameters,
the PHP processes data on the server and return a HTML
and JavaScript code that can display in your page what
they want, the traffic site, a banner, and others

TUTORIAL

a)Create a php file on the server (named "phpjs_test.php") and add


the following code:
phpjs_test.php
<?php
$ids = array(1=>'php-mysql', 2=>'javascript', 3=>'html');// gets the id from URL
if (isset($_GET['id'])) {
if ($sir = $ids[$_GET['id']]) {// return a string with a JS instruction that will display a link
echo 'document.write("<a href=\'http://coursesweb.net/'. $sir. '\'>'. $sir.
'course</a>");;
}
}

CONT
b)In the same folder on the server create a html file
(ex."test_jsphp.html") where you add the fallowing code:
test_jsphp.html
<script type="text/javascript" src="phpjs_test.php?id=2"></script>

SUMMARY

Variable

Special container that can hold a value


Create template for operation
Global-assign value presented
Operators

Symbol or series of symbol


Assignment, arithmetic, concatenation, comparison, logical operators
Constant

Can only be access by the constants name


Can be used in the scripts, including the functions stored in the
external files

CONT

Switching Flows

False code block will be ignore


Execute true expression

If, else with if statement, else-if with if statement, switch, operator.


Loops

Can perform repetitive task


Decide how many time to execute
While statement-execute if the expression is true
Do while statement-execute before the truth test
For.statement-infinite loop
Code blocks

Contain multiple echo statement


Return to HTML mode
JavaScript
Not a full programming language

Similar syntax to c, c++ and java


Platform independent

HABISS SUDAH
ADA SOALAN KAH KAMU??
PAHAM JUGA KAN...