2.
3 Control 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. Is used if you want to select one of many
blocks of code to be executed, use the Switch statement.
If statement
The if statement executes some • Example
code if one condition is true. <?php
Syntax $t = date("H");
if (condition) { if ($t < "20") {
code to be executed if condition is
true; echo "Have a
good day!";
}
}
The example below will output
"Have a good day!" if the current ?>
time (HOUR) is less than 20:
The if...else Statement
The example below will output "Have a good day!" if the current
time is less than 20, and "Have a good night!" otherwise:
• This executes some code • Example
<?php
if a condition is true and $t = date("H");
if ($t < "20") {
another code if that echo "Have a good day!";
condition is false. } else {
echo "Have a good night!";
Syntax }
?>
if (condition) {
code to be executed if
condition is true;
} else {
code to be executed if
condition is false; }
The if...elseif. else Statement
This executes different
codes for more than two example
conditions.
<?php
• Syntax $t = date("H");
if (condition) { if ($t < "10") {
code to be executed if this echo "Have a good morning!";
condition is true; } elseif ($t < "20") { echo
} elseif (condition) { "Have a good day!";
code to be executed if this } else {
condition is true; echo "Have a good night!";
} else {
}
code to be executed if all
conditions are false; } ?>
Switch Statement
The switch statement is used to perform different actions
based on different conditions. Use the switch statement to
select one of many blocks of code to be executed. Example
Syntax switch (n)
{ <?php
case label1: $favcolor = "red";
code to be executed if n=label1; break; switch ($favcolor)
case label2:
{
code to be executed if n=label2; break;
case label3: case "red":
code to be executed if n=label3; break; echo "Your favorite color is red!";
... default: break;
code to be executed if n is different from all labels; } case "blue":
echo "Your favorite color is blue!";
This is how it works: First, we have a single
expression n (most often a variable), that is evaluated break;
once. case "green":
The value of the expression is then compared with the echo "Your favorite color is green!";
values for each case in the structure.
break;
If there is a match, the block of code associated with
that case is executed. default:
Use a break to prevent the code from running into the echo "Your favorite color is neither
next case automatically. red, blue, nor green!";
The default statement is used if no match is found.
}
?>
2.4 PHP Array
• An array stores multiple values in one single variable.
• An array is a sequence of data items of the same type or
not the same type value.
• An array is used to store a collection of data, but it is often
more useful to think of an array as a collection of
variables.
• Instead of declaring individual variables, such as number0,
number1, ..., and number99, you declare one array variable
such as numbers, and use numbers[0], numbers[1], and ...,
numbers[99] to represent individual variables.
• specific element in an array is accessed by an index.
• In PHP, the array () function is used to create an array.
In PHP, there are three types of arrays:
– Indexed arrays - Arrays with a numeric index
– Associative arrays - Arrays with named keys
– Multidimensional arrays - Arrays containing one
or more arrays
1. Indexed or One-dimensional array:
Declaration and Initialization of Index or one-
dimensional array:
To declare an array in PHP, a programmer specifies
the items of the elements and the number of
elements required by an array () function as follows;
Syntax:
$ArrayName = array ( “item1”,”item2”, ..);
Example:
$age = array (25, 40, 23, 45, 76);
Here, the name of an array is age.
The size of an array is 5, i.e., there are 5 items
(elements) of array age.
All elements in an array are of the same type
(integer, in this case).
Array elements
– The size of an array defines the number of elements in an
array.
– Each element of the array can be accessed and used by the
user according to the needs of the program.
For example:
– Note that, the first element is numbered 0, the second
element 1, and so on.
Associative arrays
These types of arrays are similar to the indexed arrays but
instead of linear storage, every value can be assigned with
a user-defined key can either be an integer or a string.
The value can be of any type.
Syntax:
$ArrayName = array ( key1 => value, key2 => value2, key3 => value3,
...)
Example
<?php
$Flowers=array ("Rose"=>"Red", "Sun Flower"=>"Yellow",
"Motia"=>"White");
foreach ($Flowers as $flower => $color)
{
echo "$flower is $color ". " <br> ";
}
?>
Multidimensional arrays
• Multi-dimensional arrays are such type of arrays that stores
another array at each index instead of a single element.
• It can be created using a nested array.
• These types of arrays can be used to store any type of
element, but the index is always a number.
• A multidimensional array is an array containing one or more
arrays.
• PHP understands multidimensional arrays that are two,
three, four, five, or more levels deep.
• However, arrays more than three levels deep are hard to
manage for most people.
Example of PHP program (Multi-Dimensional Array):
<?php
$records = array ( array ("Asif","Assitant",25000),
array ("Nadeem","Accountant",3000),
array ("Farhan","Programmer",455000),
array ("Rashid","Operator",1000) );
echo "Name : Designation : Salary <br>";
echo "================================<br>";
for($row=0; $row<4; $row++){ for($col=0; $col<3; $col++){
echo $records[$row][$col]. " , " ;
}
echo "<br>";
?>
Sorting the Array
The sort () function, the elements in an array can be sorted in
alphabetical or numerical in ascending order.
In the rsort () function, the elements in an array can be
sorted in alphabetical or numerical, descending order.
Example
<?php
$salary = array (50000,40000,20000,30000,60000);
echo "Original Array values <br>"; for ($i=0; $i<=4; $i++)
{
echo " Employee $i , and Salary is $salary[$i] <br> " ;
}
echo "After Sorting Array values <br>";
sort($salary);
for ($i=0; $i<=4; $i++)
{
echo " Employee $i , and Salary is $salary[$i] <br> " ;
}
?>
• The end result of this concatenation is that the $greeting variable has a
value of Hello, world!. Because of the way PHP deals with variables, the
same effect could be accomplished using
• $greeting = "$s1$s2";
• This code works because PHP replaces variables within double quotation
marks with their value. However, the formal method of using the period
to concatenate strings is more commonly used and is recommended (it
will be more obvious what’s occurring in your code).
• Another way of performing concatenation involves the concatenation
assignment operator:
• $greeting = 'Hello, ';
• $greeting .= 'world!';
2.5 Strings and Date Time Manipulation
• A string is a sequence of Concatenating Strings
characters, like "Hello world!". Concatenation is an unwieldy term but a useful
A string can be any text inside concept.
quotes. You can use single or It refers to the appending of one item onto another.
Specifically, in programming, you concatenate strings.
double quotes:
• Example The period (.) is the operator for performing this action,
and it’s used like so:
<?php
$x = "Hello world!"; echo $s1 = 'Hello, ';
$x;
$s2 = 'world!';
echo "<br>";
$x = 'Hello world!'; echo $x; $greeting = $s1 . $s2;
?> The end result of this concatenation is that the
$greeting variable has a value of Hello, world!.
;
?>
Date Time Manipulation
Date and time are some of the most frequently used
operations in PHP while executing SQL queries or
designing a website etc.
PHP serves us with predefined functions for these
tasks.
Some of the predefined functions in PHP for date
and time are discussed below.
• PHP date() Function: The PHP date() function
converts timestamp to a more readable date and time
format.
Syntax:
date(format, timestamp)
• Explanation: The format parameter in the
date() function specifies the format of returned
date and time.
• The timestamp is an optional parameter, if it is
not included then the current date and time will
be used.
Example:
<?php
echo "Today's date is :";
$today = date("d/m/Y"); echo $today;
?>
Output:
Today's date is:05/12/2024
• Formatting options available in the date() function:
• The format parameter of the date() function is a string
that can contain multiple characters allowing generation
the of dates in various formats.
• Date-related formatting characters that are commonly
used in the format string:
• d: Represents day of the month; two digits with
leading zeros (01 or 31).
• D: Represents the day of the week in the text as an
abbreviation (Mon to Sun).
• m: Represents month in numbers with leading
zeros (01 or 12).
• M: Represents month in text, abbreviated (Jan to
Dec).
• y: Represents year in two digits (08 or 14).
• Y: Represents the year in four digits (2008 or
2014).
• The parts of the data can be separated by inserting other
characters, like hyphens (-), dots (.), slashes (/), or spaces
to add additional visual formatting.
Example:
<?php
echo "Today's date in various formats:" . "\n";
echo date("d/m/Y") . "\n";
echo date("d-m-Y") . "\n";
echo date("d.m.Y") . "\n";
echo date("d.M.Y/D");
?>
Output:
Today's date in various formats:
05/12/2024
05-12-2024
05.12.2024
[Link].2024/Tue
The following characters can be
used along with the date() function Example:
to format the time string:
• h: Represents hour in 12-hour <?php
format with leading zeros (01 to
12). echo date("h:i:s") . "\n";
• H: Represents hour in 24-hour
format with leading zeros (00 to echo date("M,d,Y h:i:s A") . "\n";
23).
• i: Represents minutes with echo date("h:i a");
leading zeros (00 to 59).
?>
• s: Represents seconds with
leading zeros (00 to 59). Output:
• a: Represents lowercase
antemeridian and post meridian 03:04:17
(am or pm).
• A: Represents uppercase Dec,05,2024 03:04:17 PM
antemeridian and post meridian
(AM or PM). 03:04 pm
•
PHP Functions
• A function is a block of code written in a program to perform
some specific task.
• We can relate functions in programs to employees in an
office in real life for a better understanding of how functions
work.
• Suppose the boss wants his employees to calculate the annual
budget.
• So how will this process completed? The employee will take
information about the statistics from the boss, perform
calculations calculate the budget, and show the result to his
boss.
• Functions work in a similar manner.
• They take information as a parameter, execute a block of
statements, or perform operations on these parameters and
return the result.
Con..
PHP provides us with two major types of functions:
– Built-in functions: PHP provides us with a huge
collection of built-in library functions. These functions
are already coded and stored in the form of functions.
To use those we just need to call them as per our
requirement like, var_dump, fopen(), print_r(), gettype()
and so on.
– User-Defined Functions: Apart from the built-in
functions, PHP allows us to create our own customized
functions called user-defined functions.
– Using this we can create our own packages of code and
use it wherever necessary by simply calling it.
Why should we use functions?
Reusability: If we have a common code that we would
like to use at various parts of a program, we can simply
contain it within a function and call it whenever
required. This reduces the time and effort of repetition
of a single code.
Easier error detection: Since our code is divided into
functions, we can easily detect in which function, the
error could lie and fix them fast and easily.
• Easily maintained: As we have used functions in our
program, if anything or any line of code needs to be
changed, we can easily change it inside the function
and the change will be reflected everywhere, where the
function is called. Hence, easy to maintain.
Creating a Function
While creating a user-defined function we need to
keep a few things in mind:
– Any name ending with an open and closed
parenthesis is a function.
– A function name always begins with the keyword
function.
– To call a function we just need to write its name
followed by the parenthesis
– A function name cannot start with a number.
– It can start with an alphabet or underscore.
– A function name is not case-sensitive.
– Syntax:
function function_name()
{
executable code;
Example:
<?php
function funcName()
{
echo "This is Alemu";
}
// Calling the function funcName();
?>
Output:
This is Alemu for Alemu
Working With Objects
• Object-oriented programming (OOP) is a popular
programming paradigm that allows developers to
create more organized, efficient, and modular
code.
• PHP is a versatile language that supports OOP.
• In PHP, a class is a blueprint for creating objects.
• It defines a set of properties and methods to be
used by the objects created from the class.
• An object is an instance of a class, which means it
has its own set of properties and methods defined
in the class.
• Creating a PHP Class
To create a class in PHP, use the class keyword
followed by the name of the class.
The class name should be in CamelCase (i.e., the
first letter of each word is capitalized) and should
be a noun that describes the purpose of the class.
Syntax
class MyClass {
// Properties and methods go here
}
Defining Properties and Methods
– Properties are variables that belong to a class, and methods are
functions that belong to a class.
– To define properties, use the public, private, or protected keyword
followed by the property name.
– Similarly, to define methods, use the public, private, or protected
keyword followed by the method name and a pair of parentheses.
Syntax
class MyClass { public $property1; private $property2;
protected $property3; public function method1() {
// Code goes here
}
private function method2() {
// Code goes here
}
protected function method3() {
// Code goes here
}}
Creating an Object
To create an object from a class, use the new keyword
followed by the class name and a pair of parentheses.
• syntax
$object1 = new MyClass();
Accessing Properties and Methods
To access the properties and methods of an object, use the
arrow operator (->) followed by the property or method
name.
Remember that you can only access public and protected
properties and methods from outside the class.
$object1->property1 = "Hello, world!";
echo $object1->property1;
// Output: Hello, world!
$object1->method1(); Example:
• Let's create a simple PHP class called Person with two properties
($firstName and $lastName) and two methods (getFullName() and
sayHello()).
<?php
class Person {
public $firstName; public $lastName;
public function getFullName() {
return $this->firstName . ' ' . $this->lastName;
}
public function sayHello() {
echo "Hello, my name is " . $this->getFullName() . ".";
}
}
$person1 = new Person();
$person1->firstName = "John";
$person1->lastName = "Doe";
$person1->sayHello(); // Output: Hello, my name is John Doe.
?>
Thanks
end of
chapter two