You are on page 1of 53

THE BASICS OF PHP SCRIPTS

 Like HTML documents, PHP files are made up of plain


text.
 You can create them with any text editor, and most popular
HTML editors.
 When writing PHP, you need to inform the PHP engine that
you want it to execute your commands.
 If you don’t do this, the code you write will be mistaken for
HTML and will be output to the browser.
 You can designate your code as PHP with special tags that
mark the beginning and end of PHP code blocks.
 Tag Style Start Tag<?php and End Tag ?>
CONT.…
 Type in the example and save the file to the document root of
your web server, using a name something like first.php.
 A Simple PHP Script

1: <?php
2: echo “<h1>Hello Web!</h1>”;
3: ?>
 Each code line in PHP must end with a semicolon.

 The semicolon is a separator and is used to distinguish one


set of instructions from another.
 We have to use the “echo” statement to print/ output the text.
COMBINING HTML AND PHP
 The script above is pure PHP.
 You can incorporate this into an HTML document by simply adding
HTML outside the PHP start and end tags, as shown in below:
<!DOCTYPE html>
<html>
<head>
<title>A PHP script including HTML</title>
</head>
<body>
<h1><?php echo “hello world”; ?></h1>
</body>
</html>
COMMENTS IN PHP
 A commentis text in a script that is ignored by the PHP engine.
 Comments can make code more readable or annotate a script.
 In PHP, we use
 Single-line comments that begin with two forward slashes (//) —

// The PHP engine ignores all text till the end of the line
 Multiline comments that begin with a forward slash followed by an
asterisk (/*) and end with an asterisk followed by a forward
slash (*/):
 /*
 this is a comment

 none of this will

 be parsed by the

 PHP engine

 */
VARIABLES
 A variable is a special container that you can define, which
then “holds” a value, such as a number, string, or array.
 When a variable is set it can be used over and over again in
your script
 Without variables, you would be forced to hard-code each
specific value used in your scripts.
 All variable consists of a name of your choosing, preceded by
a dollar sign ($).
 The correct way of setting a variable in PHP:

 $var_name = value;
CONT.…
 In PHP a variable does not need to be declared
before being set.
 In the PHP you do not have to tell which data type
the variable is.
 PHP automatically converts the variable to the
correct data type, depending on how they are set.
 In a strongly typed programming language, you
have to declare (define) the type and name of the
variable before using it.
VARIABLE NAMING RULES
 Variable names can include letters, numbers, and the
underscore character (_).
 A variable name must start with a letter or an underscore "_"

 A variable name should not contain spaces.

 Example: - <?php
$txt="Hello World";
echo $txt;
$num1 = 8;
echo 8;
$letter = s;
echo letter; ?>
OPERATORS AND EXPRESSIONS
 Operator is a symbol or series of symbols that, when used in
conjunction with values, performs an action, and usually
produces a new value.
 A value operated on by an operator is referred to as an
operand.
 An operand is a value used in conjunction with an
operator.
 Example: (4 + 5)
 The integers 4 and 5 are operands.
 The addition operator (+) operates on these operands to
produce the integer 9.
 The combination of operands with an operator to produce a
result is called an expression.
ARITHMETIC OPERATORS

Operator Description

+ Addition

- Subtraction

* Multiplication

/ Division

% Modulus

++ Increment

-- Decrement
COMPARISON OPERATORS
Operator Description

== equal to  .
=== equal value and equal type
!= not equal
!== not equal value or not equal type

.> greater than


< less than
>= greater than or equal to
<= less than or equal to
? ternary operator
ASSIGNMENT OPERATORS

Operator Example Same As


 .
= x=y x=y

+= x += y x=x+y

-= x -= y x=x-y
.
*= x *= y x=x*y

/= x /= y x=x/y

%= x %= y x=x%y
LOGICAL OPERATORS
Operator Description

&& 
logical and .
|| logical or

! logical not

.
OPERATOR PRECEDENCE
STRING OPERATOR
 The concatenation operator (.)
 It is used to put two string values together.
 use the dot (.) operator:
 Example:

<?php
$txt1="Hello World";
$txt2="1234";
echo $txt1 . " " . $txt2;
?>
 Output:

Hello World 1234


CONT.…
 The strlen() function:
 It is used to find the length of a string.
 Let's find the length of our string "Hello world!":
 Example:

<?php
echo strlen("Hello world!");
?>
 The output of the code above will be:

12
CONT.…
 The strpos() function:
 It is used to search for a string or character.
 If a match is found in the string, this function will return
the position of the first match.
 If no match is found, it will return FALSE.
 Example:

<?php
echo strpos("Hello world!","world");
?>
 The output will be: 6
 The position is 6, and not 7, because the first position in the
string is 0, and not 1.
CONT.:
 The str_replace():
 It replaces all occurrences of the search text within the
target string.
 Example

<?php
$my_str = 'If the facts do not fit the theory, change the
facts.';
echo str_replace("facts", "truth", $my_str);
?>
The output of the above code will be:
If the truth do not fit the theory, change the
truth.
COMPLETE PHP STRING REFERENCE:

 For a complete reference of all string functions, go to the


W3C complete PHP String Reference.

 http://w3schools.com/php/php_ref_string.asp

 The reference contains a brief description and examples


of use for each function!
SELECTION CONDITIONAL
STATEMENTS
 PHP control statements are the same as any other programming
language
 There are several statements in PHP that you can use to make
decisions:
 PHP also allows you to write code that perform different actions
based on the results of a logical or comparative test conditions at run
time.
 This means, you can create test conditions in the form of
expressions that evaluates to either true or false and
 Based on these results you can perform certain actions.

 The if statement
 The if...else statement
 The if...elseif....else statement
 The switch...case statement
The if statement
 The if statement is used to execute a block of code only if the
specified condition evaluates to true.
 This is the simplest PHP's conditional statements and can be written
like:
if(condition){
// Code to be executed
}
 The following example will output "Have a nice weekend!" if the
current day is Friday:
<?php
$d = “Fri";
if($d == "Fri"){
echo "Have a nice weekend!";
}
?>
The if...else Statement
 The if...else statement allows you to execute one block of code if
the specified condition is evaluates to true and another block of
code if it is evaluates to false.
 It can be written, like this:

if(condition){
    // Code to be executed if condition is true
} else{
    // Code to be executed if condition is false
}
 Example
<?php $d = “Fri";
if($d == “Fri")
{ echo "Have a nice weekend!"; }
else { echo "Have a nice day!"; }
?>
The if...elseif...else Statement
 The if...elseif...else a special statement that is used to combine multiple
if...else statements.
if(condition){
    // Code to be executed if condition is true
} elseif(condition){
    // Code to be executed if condition is true
} else{
    // Code to be executed if condition is false
}
 Example
<?php
$d = “Fri";
if($d == "Fri")
{ echo "Have a nice weekend!"; }
elseif($d == "Sun") { echo "Have a nice Sunday!"; }
else { echo "Have a nice day!"; }
?>
PHP Switch…Case Statements
 Theswitch-case statement tests a variable against a series of
values until it finds a match, and then executes the block of
code corresponding to that match.
switch(n){
    case label1:
        // Code to be executed if n=label1
        break;
    case label2:
        // Code to be executed if n=label2
        break;
    ...
    default:
        // Code to be executed if n is different from all labels
}
PHP Switch…Case Statements. . . Example
<?php case "Fri":
$today = “Mon"; echo "Today is Friday. The
switch($today){ weekend! .";
case "Mon": break;
echo "Today is Monday. Clean your case "Sat":
dorm."; echo "Today is Saturday. Its movie
break; time.";
case "Tue": break;
echo "Today is Tuesday. Buy some case "Sun":
food."; echo "Today is Sunday. Do some
break; rest.";
case "Wed": break;
echo "Today is Wednesday. AIP Class default:
."; echo "No information available.";
break; break;
case "Thu": }
echo "Today is Thursday. Clean ?>
your Lab.";
break;
CONT.…
 Php switch statements
 Case: it takes a single variable as input and then checks it against all the
different cases you set up for that switch statement (e.g. case November:
Output: Current Month!)
 Break (to stop executing all the cases that follow the correct case)
 Default case (when the variable doesn’t match all conditions, no case
before default default:)
Loops in PHP
 Scripts can decide how many times to execute a block of
code.
 Loop statements are designed to enable you to achieve
repetitive tasks.
 A loop will continue to operate until a condition is
achieved, or you explicitly choose to exit the loop.
 Loops are used frequently in scripts to set up a block of
statements that repeat.
CONT.…
 PHP supports following four loop types.
 for - loops through a block of code a specified number
of times.
 while - loops through a block of code if and as long as
a specified condition is true.
 do...while - loops through a block of code once, and
then repeats the loop as long as a special condition is
true.
 foreach - loops through a block of code for each
element in an array.
For Loops in PHP
 It is used when you know how many times you want to execute
a statement or a block of statements.
 Syntax: for (initialization; condition; increment)

{
code to be executed;
}
While Loops in PHP
 The while statement will execute a block of code if and as long
as a test expression is true.
 If the test expression is true then the code block will be executed
and the loop will continue until the test expression is found to be
false.
 Syntax: while (condition is true) {
    code to be executed;
}
Do…while Loops in PHP
 It will always execute the block of code once, it will
then check the condition, and repeat the loop while the
specified condition is true.
 Syntax do {
   code to be executed;
} while (condition is true);
Foreach Loops in PHP
 The foreach statement is used to loop through arrays.
 For each pass the value of the current array element is assigned
to $value and the array pointer is moved by one and in the next
pass next element will be processed.
 Syntax

foreach (array as value)


{
code to be executed;
}
Breaking out of a Loops in PHP
Sometimes you want your script to break out of a loop.
PHP provides two statements for this purpose:
 break: breaks completely out of a loop and continues
with the script statements after the loop.
 continue: stops current iteration and goes back to
condition check. If condition check is true, it will go to
the next iteration.
The break and continue statements are usually used in
conditional statements. In particular, break is used most
often in switch statements.
Cont.…
Cont.…
FUNCTION
 A function is a block of code that can be executed whenever we
need it.
 When called, the function’s code is executed and performs a
particular task.
 You can pass values to a function, which then uses the values
appropriately.
 When finished, a function can also pass a value back to the
original code that called it into action.
DEFINING A FUNCTION
 You can define your own functions using the function statement:
function f_name($argument1, $argument2)
{
//function code here
}
 Example:

<?php
function bighello()
{ echo “<h1>HELLO!</h1>”; }
bighello();
?>
CONT.…
 Declaring a Function That Requires an Argument
 <?php

 function printBR($txt)

{

 echo $txt.”<br/>”;

 }

 printBR(“This is a line.”);

 printBR(“This is a new line.”);

 printBR(“This is yet another line.”);

 ?>
CONT.…
 The following function has two parameters:
 <?php

 function writeMyName($fname,$punctuation)

 {

 echo $fname . " Smith" . $punctuation . "<br />";

 }

 echo "My name is ";

 writeMyName("John",".");

 echo "My name is ";

 writeMyName("Sarah","!");

 echo "My name is ";

 writeMyName("Smith","...");

 ?>
PHP FUNCTIONS - RETURN VALUES
 Functions can also be used to return values.
 <html>

 <body>

 <?php

 function add($x,$y)

 {

 $total = $x + $y;

 return $total;

 }

 echo "1 + 16 = " . add(1,16);

 ?>

 </body>

 </html>
PHP ARRAYS
 An array can store one or more values in a single
variable name.
 An array can hold multiple, separate pieces of
information.
 It is therefore like a list of values, each value being a
string or a number or even another array.
 For each item in the list, there is a key (or index)
associated with it
 An array follows the same naming rules as any other
variable.
CONT.…
 Arrays are indexed, which means that each entry is
made up of a key and a value.
 The key is the index position, beginning with 0 and
increasing incrementally by 1 with each new element in
the array.
 The value is whatever value you associate with that
position—a string, an integer, or whatever you want.
CREATING ARRAYS
 You can create an array using either the array( ) function or the
array operator [ ].
 The array( ) function is usually used when you want to create a
new array and populate it with more than one element, all in one
fell swoop.
 $rainbow = array(“red”, “orange”, “yellow”, “green”, “blue”,
“indigo”)
 The array operator is often used when you want to create a new
array with just one element at the outset, or when you want to add
to an existing array element.
 $rainbow[ ] = “red”;
 $rainbow[ ] = “orange”;
 $rainbow[ ] = “yellow”; cont…
TYPES OF ARRAYS
 There are three different kind of arrays.
 In php there are three types of arrays:

 Indexed/Numeric array - An array with a numeric ID


key
 Associative array - An array with named (string) keys
 Multidimensional array - An array containing one or
more arrays
NUMERIC ARRAYS
 A numeric array stores each element with a numeric ID key.
 There are different ways to create a numeric array.

 Example 1: the ID key is automatically assigned:


 $names = array("Peter","Quagmire","Joe");

 Example 2: we assign the ID key manually:


 $names[0] = "Peter";
 $names[1] = "Quagmire";
 $names[2] = "Joe";
CONT.…
 Example:

<?php
$names[0] = "Peter";
$names[1] = "Quagmire";
$names[2] = "Joe";
echo $names[1] . " and " . $names[2] .
" are ". $names[0] . "'s neighbours";
?>

 The
code above will output:
Quagmire and Joe are Peter's neighbours
ASSOCIATIVE ARRAYS
 When storing data about specific named values, a numerical
array is not always the best way to do it.
 With associative arrays we can use the values as keys and
assign values to them.
 Example 1: we use an array to assign ages to the different
persons:
 $ages = array("Peter"=>32, "Quagmire"=>30,
"Joe"=>34);
 Example 2: shows a different way of creating the array:

 $ages['Peter'] = "32";
 $ages['Quagmire'] = "30";
 $ages['Joe'] = "34";
CONT.…
 Example:

<?php
$ages['Peter'] = "32";
$ages['Quagmire'] = "30";
$ages['Joe'] = "34";
echo "Peter is " . $ages['Peter'] . " years old.";
?>

 Thecode above will output:


Peter is 32 years old.
MULTIDIMENSIONAL ARRAY
 Ina multidimensional array, each element in the main array
can also be an array.
 And each element in the sub-array can be an array, and so
on.
 Values in the multi-dimensional array are accessed using
multiple index.
 For a two-dimensional array you need two indices to
select an element
 For a three-dimensional array you need three indices to
select an element
SOME ARRAY-RELATED FUNCTIONS
 More than 70 array-related functions are built in to PHP,
which you can read about in detail at http://
www.php.net/array
 Some of the more common functions are :

 count() and sizeof()—Each of these functions counts the


number of elements in an array; they are aliases of each
other.
 $colors = array(“blue”, “black”, “red”, “green”);
 both count($colors); and sizeof($colors); return a value of
4.
CONT.…
 sort() - sort arrays in ascending order
 rsort() - sort arrays in descending order

 array_push()—This function adds one or more elements to


the end of an existing array, as in this example:
 array_push($existingArray, “element 1”, “element 2”,
“element 3”);
 array_pop()—This function removes (and returns) the last
element of an existing array, as in this example:
 $last_element = array_pop($existingArray);
CONT.…
 array_unshift()—This function adds one or more elements to
the beginning of an existing array, as in this example:
 array_unshift($existingArray, “element 1”, “element 2”,
“element 3”);
 array_shift()—This function removes (and returns) the first
element of an existing array, as in this example:
 $first_element = array_shift($existingArray);
 array_merge()—This function combines two or more existing
arrays, as in this example:
 $newArray = array_merge($array1, $array2);
Cont.….

You might also like