Lesson 05

Download as pdf or txt
Download as pdf or txt
You are on page 1of 49

Part 1: PHP Functions

2
1. PHP Built-in Functions
• A function is a self-contained block of code that performs a
specific task.
• PHP has a huge collection of internal or built-in functions
that you can call directly within your PHP scripts to perform
a specific task, like gettype(), print_r(),
var_dump, etc.
• Few of built-in functions are listed next.

3
PHP Date and Time Functions
Operator Name
checkdate() Validates a Gregorian date
date_add() Adds an amount of days, months, years, hours, minutes & seconds to a date
date_create_from_for
Returns a new DateTime object formatted according to the specified format
mat()
date_create() Returns new DateTime object
date_date_set() Sets a new date
date_diff() Returns the difference between two dates
date_format() Returns a date formatted according to a specified format
date_interval_create_
Sets up a DateInterval from the relative parts of the string
from_date_string()
date_modify() Modifies the timestamp
date_parse() Returns associative array with detailed info about a specified date
Subtracts an amount of days, months, years, hours, minutes and seconds
date_sub() from a date
date_time_set() Sets the time
date_timestamp_get() Returns the Unix timestamp representing the date
date_timestamp_set() Sets the date and time based on an Unix timestamp
date() Formats a local date and time
getdate() Returns date/time information of the timestamp or the current local date/time
gettimeofday() Returns the current time
idate() Formats a local time/date as integer
localtime() Returns the local time
time() Returns the current time as a Unix timestamp
4
timezone_name_get() Returns the name of the timezone
2. PHP User-defined Functions
• In addition to the built-in functions, PHP also allows you to define
your own functions.
• It is a way to create reusable code packages that perform specific
tasks and can be kept and maintained separately form main
program.
• Here are some advantages of using functions:
• Functions reduces the repetition of code within a program - Function
allows you to extract commonly used block of code into a single component.
• Functions makes the code much easier to maintain - Since a function
created once can be used many times, any changes made inside a function
automatically implemented at all the places without touching several files.
• Functions makes it easier to eliminate the errors - When the program is
subdivided into functions, if any error occur you know exactly what function
causing the error and where to find it.
• Functions can be reused in other application - Because a function is
separated from the rest of the script, it's easy to reuse the same function in
other applications.

5
Creating and Invoking Functions
• The basic syntax of creating a custom function can be give with:
function functionName(){
// Code to be executed
}

• The declaration of a user-defined function start with the word


function, followed by the name of the function you want to
create followed by parentheses i.e. () and finally place your
function's code between curly brackets {}.
• Example of a user-defined function:
<?php
// Defining function
function writeMessage(){
echo “You are a nice person. Have a nice day!”;
}
// Calling function
writeMessage();
?>
6
Functions with Parameters
• PHP gives the option to specify parameters inside a
function to accept input values at run time.
• The parameters work like placeholder variables within a
function; they're replaced at run time by the values (known
as argument) provided to the function at the time of
invocation.
function myFunc($oneParameter, $anotherParameter){
// Code to be executed
}

• For each parameter you specify, a corresponding argument


needs to be passed to the function when it is called.
• The getSum() function in following example takes two
integer values as arguments, simply add them together and
then display the result in the browser.
7
Functions with Parameters
<?php
// Defining function
function getSum($num1, $num2){
$sum = $num1 + $num2;
echo "Sum of the two numbers $num1 and $num2 is : $sum";
}

// Calling function
getSum(10, 20);
?>

• The output of the above code will be:


Sum of the two numbers 10 and 20 is : 30

8
Functions with Optional Parameters and Default Values
• PHP allows to create functions with optional parameters — just
insert the parameter name, followed by an equals (=) sign,
followed by a default value, like this.
<?php
// Defining function
function customFont($font, $size=1.5){
echo "<p style=\"font-family: $font; font-size: {$size}em;
\">Hello, world!</p>";
}

// Calling function
customFont("Arial", 2);
customFont("Times", 3);
customFont("Courier");
?>
• The third call to customFont() doesn't include the second
argument. This causes PHP engine to use the default value for the
$size parameter which is 1.5.
9
Returning Values from a Function
• A function can return a value back to the script that
called the function using the return statement. The
value may be of any type, including arrays and objects.
<?php
// Defining function
function getSum($num1, $num2){
$total = $num1 + $num2;
return $total;
}

// Printing returned value


echo getSum(5, 10); // Outputs: 15
?>

• A function cannot return multiple values. However, you


can obtain similar results by returning an array

10
Passing Arguments to a Function
• In PHP there are two ways you can pass arguments to a function:
• By value - By default, function arguments are passed by value so that if the
value of the argument within the function is changed, it does not get affected
outside the function.
• By reference - To allow a function to modify its arguments, they must be
passed by reference. Passing an argument by reference is done by
prepending an ampersand (&) to the argument name in the function
definition, as shown in the example below:
<?php
/* Defining a function that multiply a number
by itself and return the new value */
function selfMultiply(&$number){
$number *= $number;
return $number;
}

$mynum = 5;
echo $mynum; // Outputs: 5

selfMultiply($mynum);
echo $mynum; // Outputs: 25
?>

11
Understanding the Variable Scope
• Variables can be declared anywhere in a PHP script.
• But, the location of the declaration determines the extent of a
variable's visibility within the PHP program i.e. where the variable can
be used or accessed. This accessibility is known as variable scope.
• By default, variables declared within a function are local and they
cannot be viewed or manipulated from outside of that function, as
demonstrated in the example below:
<?php
// Defining function
function test(){
$greet = "Hello World!";
echo $greet;
}

test(); // Outputs: Hello World!

echo $greet; // Generate undefined variable error


?>

12
Understanding the Variable Scope
• Similarly, if you try to access or import an outside variable inside the
function, you'll get an undefined variable error, as shown in the following
example:
<?php
$greet = "Hello World!";

// Defining function
function test(){
echo $greet;
}

test(); // Generate undefined variable error

echo $greet; // Outputs: Hello World!


?>
• As you can see in the above examples the variable declared inside the
function is not accessible from outside, likewise the variable declared
outside of the function is not accessible inside of the function.
• This separation reduces the chances of variables within a function getting
affected by the variables in the main program.
13
The global Keyword
• There may be a situation when you need to import a variable from the main
program into a function, or vice versa. In such cases, you can use global
keyword before the variables inside a function.
• This keyword turns the variable into a global variable, making it visible or
accessible both inside and outside the function, as show in the example below:
<?php
$greet = "Hello World!";

// Defining function
function test(){
global $greet;
echo $greet;
}

test(); // Outpus: Hello World!


echo $greet; // Outpus: Hello World!

// Assign a new value to variable


$greet = "Goodbye";

test(); // Outputs: Goodbye


echo $greet; // Outputs: Goodbye
?>

14
Part 2: PHP Control Structures

15
PHP Conditional Statements
• PHP 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.
• There are several statements in PHP that you can use to
make decisions:
- The if statement
- The if...else statement
- The if...elseif....else statement
- The switch...case statement

16
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 = date("D");
if($d == "Fri"){
echo "Have a nice weekend!";
}
?>
17
The if...else Statement
• You can enhance the decision making process by providing an
alternative choice through adding an else statement to the if
statement.
if(condition){
// Code to be executed if condition is true
} else{
// Code to be executed if condition is false
}

• The following example will output "Have a nice weekend!" if the


current day is Friday, otherwise it will output "Have a nice day!"
<?php
$d = date("D");
if($d == "Fri"){
echo "Have a nice weekend!";
} else{
echo "Have a nice day!";
}
?>
18
The if...elseif...else Statement
• The if...elseif...else a special statement that is used to combine multiple
if...else statements.
if(condition1){
// Code to be executed if condition1 is true
} elseif(condition2){
// Code to be executed if the condition1 is false and condition2 is true
} else{
// Code to be executed if both condition1 and condition2 are false
}

• The following example will output "Have a nice weekend!" if the current day
is Friday, and "Have a nice Sunday!" if the current day is Sunday, otherwise
it will output "Have a nice day!"
<?php
$d = date("D");
if($d == "Fri"){
echo "Have a nice weekend!";
} elseif($d == "Sun"){
echo "Have a nice Sunday!";
} else{
echo "Have a nice day!";
}
?>
19
The Ternary Operator
• The ternary operator provides a shorthand way of writing the
if...else statements. It is represented by the question mark (?)
symbol and it takes three operands:
• a condition to check
• a result for true
• a result for false
<?php
if($age < 18){
echo 'Child'; // Display Child if age is less than 18
} else{
echo 'Adult'; // Display Adult if age is greater than or equal to
18
}
?>

• Using the ternary operator the same code could be written in a


more compact way:
<?php echo ($age < 18) ? 'Child' : 'Adult'; ?>
20
The Null Coalescing Operator PHP 7
• PHP 7 introduces a new null coalescing operator (??)
which you can use as a shorthand where you need to use
a ternary operator in conjunction with isset() function.
• To uderstand this in a better way consider the following
line of code. It fetches the value of $_GET['name'], if it
does not exist or NULL, it returns 'anonymous'.
<?php
$name = isset($_GET['name']) ? $_GET['name'] :
'anonymous';
?>
• The Using the null coalescing operator the same code
could be written as:
<?php
$name = $_GET['name'] ?? 'anonymous';
?>
21
PHP Switch…Case Statements
• The switch-case statement is an alternative to the if-
elseif-else statement, which does almost the same thing.
• The switch-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
}

22
Example - Switch…Case Statements
<?php
$today = date("D");
switch($today){
case "Mon":
echo "Today is Monday. Clean your house.";
break;
case "Tue":
echo "Today is Tuesday. Buy some food.";
break;
case "Wed":
echo "Today is Wednesday. Visit a doctor.";
break;
case "Thu":
echo "Today is Thursday. Repair your car.";
break;
case "Fri":
echo "Today is Friday. Party tonight.";
break;
case "Sat":
echo "Today is Saturday. Its movie time.";
break;
case "Sun":
echo "Today is Sunday. Do some rest.";
break;
default:
echo "No information available for that day.";
break;
}
?>

• The switch-case statement differs from the if-elseif-else statement in one important way. The
switch statement executes line by line (i.e. statement by statement) and once PHP finds a
case statement that evaluates to true, it's not only executes the code corresponding to that
case statement, but also executes all the subsequent case statements till the end of the
switch block automatically.
• To prevent this add a break statement to the end of each case block. 23
Part 3: PHP Iterative Structures

24
PHP Loops
• Loops are used to execute the same block of code
again and again, until a certain condition is met.
• The basic idea behind a loop is to automate the
repetitive tasks within a program to save the time and
effort.
• PHP supports four different types of loops.
- while - loops through a block of code until the condition is evaluate
to true
- do…while - the block of code executed once and then condition is
evaluated. If the condition is true the statement is repeated as long
as the specified condition is true.
- for - loops through a block of code until the counter reaches a
specified number.
- foreach - loops through a block of code for each element in an array

25
PHP while Loop
• The while statement will loops through a block of code
until the condition in the while statement evaluate to true.
while(condition){
// Code to be executed
}

• The example below define a loop that starts with $i=1. The
loop will continue to run as long as $i is less than or equal
to 3. The $i will increase by 1 each time the loop runs:
<?php
$i = 1;
while($i <= 3){
$i++;
echo "The number is " . $i . "<br>";
}
?>

26
PHP do…while Loop
• The do-while loop is a variant of while loop, which evaluates the condition
at the end of each loop iteration.
• With a do-while loop the block of code executed once, and then the
condition is evaluated, if the condition is true, the statement is repeated as
long as the specified condition evaluated to is true.
do{
// Code to be executed
}
while(condition);

• The following example define a loop that starts with $i=1. It will then
increase $i with 1, and print the output. Then the condition is evaluated, and
the loop will continue to run as long as $i is less than, or equal to 3.
<?php
$i = 1;
do{
$i++;
echo "The number is " . $i . "<br>";
}
while($i <= 3);
?>

27
Difference Between while and do…while Loop
• The while loop differs from the do-while loop in one
important way,
• with a while loop, the condition to be evaluated is
tested at the beginning of each loop iteration, so if
the conditional expression evaluates to false, the
loop will never be executed.
• With a do-while loop, on the other hand, the loop
will always be executed once, even if the conditional
expression is false, because the condition is
evaluated at the end of the loop iteration rather than
the beginning.

28
PHP for Loop
• The for loop repeats a block of code until a certain condition is met. It
is typically used to execute a block of code for certain number of times.
for(initialization; condition; increment){
// Code to be executed
}

• The parameters of for loop have following meanings:


- initialization - used to initialize the counter variables, and evaluated
once unconditionally before the first execution of the body of the
loop.
- condition - in the beginning of each iteration, condition is evaluated.
If it evaluates to true, the loop continues and the nested statements
are executed. If it evaluates to false, the execution of the loop ends.
- increment - it updates the loop counter with a new value. It is
evaluate at the end of each iteration.
<?php
for($i=1; $i<=3; $i++){
echo "The number is " . $i . "<br>";
}
?>
29
PHP foreach Loop
• The foreach loop is used to iterate over arrays.
foreach($array as $value){
// Code to be executed
}

• The following example demonstrates a loop that will


print the values of the given array:
<?php
$colors = array("Red", "Green", "Blue");

// Loop through colors array


foreach($colors as $value){
echo $value . "<br>";
}
?>

30
PHP foreach Loop
• There is one more syntax of foreach loop, which is
extension of the first.
foreach($array as $key => $value){
// Code to be executed
}

<?php
$superhero = array(
"name" => "Peter Parker",
"email" => "[email protected]",
"age" => 18
);

// Loop through superhero array


foreach($superhero as $key => $value){
echo $key . " : " . $value . "<br>";
}
?>
31
Part 4: PHP Classes

32
PHP Classes
• A class is a self-contained, independent collection of
variables and functions which work together to perform one
or more specific tasks, while objects are individual instances
of a class.
• A class acts as a template or blueprint from which lots of
individual objects can be created.
• For example, think of a class as a blueprint for a house. The
blueprint itself is not a house, but is a detailed plan of the
house. While, an object is like an actual house built
according to that blueprint. We can build several identical
houses from the same blueprint, but each house may have
different paints, interiors and families inside.

33
PHP Classes
• A class can be declared using the class keyword, followed by the name of the
class and a pair of curly braces ({}), as shown in the following example.
• Create a PHP file named Rectangle.php with the following example code.
<?php
class Rectangle
{
// Declare properties
public $length = 0;
public $width = 0;

// Method to get the perimeter


public function getPerimeter(){
return (2 * ($this->length + $this->width));
}

// Method to get the area


public function getArea(){
return ($this->length * $this->width);
}
}
?>

34
Part 5: Arrays and associated
operations

35
PHP Array Functions
Operator Name
array() Create an array
array_column() Return the values from a single column in the input array
array_filter() Filters elements of an array using a user-defined function
array_keys() Return all the keys or a subset of the keys of an array
array_map() Sends the elements of the given arrays to a user-defined function
array_pop() Removes and return the last element of an array
array_push() Inserts one or more elements to the end of an array
array_replace() Replaces the values of the first array with the values from following arrays
array_reverse() Return an array with elements in reverse order
array_search() Searches an array for a given value and returns the corresponding key
array_sum() Calculate the sum of values in an array
array_unique() Removes duplicate values from an array
array_values() Return all the values of an array
count() Count all elements in an array
current() Return the current element in an array
each() Return the current key and value pair from an array and advance the array cursor
in_array() Checks if a value exists in an array
list() Assign variables as if they were an array
sizeof() Count all elements in an array
sort() Sort an array in ascending order 36
PHP Arrays
• A PHP array is a variable that stores more than one piece of
related data in a single variable.
• Think of an array as a box of chocolates with slots inside.
• The box represents the array itself while the spaces
containing chocolates represent the values stored in the
arrays.
1 2 3 Array

Array values

37
PHP Numeric Arrays
• Numeric arrays use number as access keys.
• An access key is a reference to a memory slot in an array
variable.
• The access key is used whenever we want to read or assign
a new value an array element.
<?php
$variable_name[n] = value;
?>
Or
<?php
$variable_name = array(n => value, …);
?>
HERE,
• “$variable_name…” is the name of the variable
• “[n]” is the access index number of the element
• “value” is the value assigned to the array element.
38
PHP Numeric Arrays - Example
<?php
$movie[0] = "Shaolin Monk";
$movie[1] = "Drunken Master";
$movie[2] = "American Ninja";
$movie[3] = "Once upon a time in China";
$movie[4] = "Replacement Killers";
echo $movie[3];
$movie[3] = " Eastern Condors";
echo $movie[3];
?>
Output:
Once upon a time in China Eastern Condors

<?php
$movie = array(0 => “Shaolin Monk”,
1 => "Drunken Master”,
2 => "American Ninja”,
3 => "Once upon a time in China”,
4 => "Replacement Killers”);
?>
39
Loop through a Numeric Array/Indexed Array
<?php
$cars = array("Volvo", "BMW", "Toyota");
$arrlength = count($cars);

for($x = 0; $x < $arrlength; $x++) {


echo $cars[$x];
echo "<br>";
}
?>

Output:
Volvo
BMW
Toyota

40
PHP Associative Arrays
• Associative array differ from numeric array in the sense that
associative arrays use descriptive names for id keys.
<?php
$variable_name[‘key_name’] = value;
?>
Or
<?php
$variable_name = array(keyname => value, …);
?>
HERE,
• “$variable_name…” is the name of the variable
• “[key_name]” is the access index number of the element
• “value” is the value assigned to the array element.

41
PHP Associative Arrays - Example
<?php
$persons = array("Mary" => "Female",
"John" => "Male",
"Mirriam" => “Female");
echo($persons);
echo “";
echo "Mary is a " . $persons["Mary"];
?>

Output:
Array ( [Mary] => Female [John] => Male [Mirriam] => Female ) Mary is a Female

42
Loop through an Associative Array
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");

foreach($age as $x => $x_value) {


echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
?>

Output:
Key=Peter, Value=35
Key=Ben, Value=37
Key=Joe, Value=43

43
PHP Multi-dimensional Arrays
• These are arrays that contain other nested arrays.
• The advantage of multidimensional arrays is that they allow
us to group related data together.
<?php
$movies array(
"comedy" => array("Pink Panther", "John English", "The Spy"),
"action" => array("Die Hard", "Expendables"),
"epic" => array("The Lord of the rings"),
"romance" => array("Romeo and Juliet”)
);
print_r($movies);
?>

Output:
Array ( [comedy] => Array ( [0] => Pink Panther [1] => John English [2] => The
spy ) [action] => Array ( [0] => Die Hard [1] => Expendables ) [epic] => Array
( [0] => The Lord of the rings ) [Romance] => Array ( [0] => Romeo and Juliet ) )

44
PHP Multi-dimensional Arrays
• Another way to define the same array is as follows
<?php
$movies array(
"comedy" => array(
0 => "Pink Panther",
1 => "John English",
2 => "The Spy”
),
"action" => array(
0 => "Die Hard",
1 => "Expendables"
),
"epic" => array(
0 => "The Lord of the rings”
),
"romance" => array(
0 => "Romeo and Juliet”
)
);
echo $movies[“comedy”][0];
?>

Output:
Pink Panther

45
Viewing Array Structure and Values
• The structure and values of any array can be viewed by using one of two
statements — var_dump() or print_r().
• The print_r() statement, however, gives somewhat less information.
<?php
// Define array
$cities = array("London", "Paris", "New York");

// Display the cities array


print_r($cities);
?>
Output:
Array ( [0] => London [1] => Paris [2] => New York )

<?php
// Define array
$cities = array("London", "Paris", "New York");

// Display the cities array


var_dump($cities);
?>
Output:
array(3) { [0]=> string(6) "London" [1]=> string(5) "Paris" [2]=> string(8) "New York" }
46
Part 6: Strings and associated
operations

47
PHP String Functions
Operator Name
chr() Returns a one-character string containing the character specified by ASCII
chunk_split() Split a string into smaller chunks
echo() Output one or more strings
fprintf() Write a formatted string to a specified output stream
join() Return a string by joining the elements of an array with a specified string
ord() Returns the ASCII value of the first character of a string
print() Output a string
printf() Output a formatted string
sprintf() Return a formatted string
str_repeat() Repeats a string a specified number of times
str_replace() Replace all occurrences of the search string with the replacement string
str_split() Splits a string into an array
str_word_count() Counts the number of words in a string
strcmp() Binary safe comparison of two string (case sensitive)
strlen() Returns the length of a string
strtolower() Converts a string to lowercase
strtoupper() Converts a string to uppercase
substr() Return a part of a string
trim() Removes whitespace (or other characters) from the beginning and end of a string
48
PHP String Functions
Creating Strings Using Single quotes
<?php
var_dump(“You need to be logged in to view this page”);
?>
Output:
string(42) "You need to be logged in to view this page"

PHP Create Strings Using Double quotes


• The double quotes are used to create relatively complex strings compared
to single quotes. Variable names can be used inside double quotes and
their values will be displayed.
<?php
$name = ‘Alicia’;
echo “$name is friends with kalinda”;
?>
Output:
Alicia is friends with kalinda
49
Questions?
Thank You

50

You might also like