PHP Learning Unit 1,2

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

[1]

Learning Unit 1: PHP Environment

1.1.Select tools and materials

The PHP Hypertext Preprocessor (PHP) is a programming language that allows web developers to
create dynamic content that interacts with databases. PHP is basically used for developing web based
software applications.

PHP is a server-side and general-purpose scripting language that is especially suited for web
development.

PHP originally stood for Personal Home Page. However, now, it stands for Hypertext
Preprocessor. It’s a recursive acronym because the first word itself is also an acronym.

PHP was created by Rasmus Lerdorf in 1994. It’s currently maintained by the PHP Development
Team.

The following illustrates how PHP works:

• First, the web browser sends an HTTP request to the web server, e.g., index.php.
• Second, the PHP preprocessor that locates on the web server processes PHP code to
generate the HTML document.
• Third, the web server sends the HTML document back to the web browser.

Advantages of PHP

Since PHP is designed for the web in the first place, it brings many advantages to web development:
[2]

• Simple – PHP is quite easy to learn and get started.


• Fast – PHP websites typically run very fast.
• Stable – PHP is stable since it has been in existence for a long time.
• Open-source and free – PHP is open source and free. It means that you don’t have to pay a
license fee to use PHP to develop software products.
• Community support – PHP has an active online community that helps you whenever you
face an issue.

Integrated Development Environment IDEs

An integrated development environment (IDE) is a software application that helps programmers


develop software code efficiently. It increases developer productivity by combining capabilities
such as software editing, building, testing, and packaging in an easy-to-use application.

History of IDE

Prior to IDEs, programmers wrote their programs in text editors. This involved writing and saving
an application in the text editor before running run the compiler, taking note of any error messages,
and then going back to the text editor to revise their code.

It wasn’t until 1983 that Borland Ltd. acquired a Pascal compiler and published it as TurboPascal,
featuring an integrated editor and compiler for the very first time.

TurboPascal may have launched the idea of an integrated development environment, but many
believe Microsoft’s Visual Basic (VB), which was launched in 1991, was actually the first real IDE
in history. Built in the older BASIC language, Visual Basic was a popular programming language
through the 1980s. The rise of Visual Basic meant that programming could instead be thought of in
graphical terms, and noteworthy productivity benefits became apparent.

Different Types of IDE

There are many ways developers work to product the different types of code they produce, which
means there is also a variety of IDEs to use.

Multi-Language IDE

The multi-language IDEs – like Eclipse, Aptana, Komodo, NetBeans, and Geany – support multiple
programming languages.
[3]

• Eclipse: Supports C, C++, Perl, Python, Ruby, PHP, Java and others. It is a free and open
source editor for many development frameworks. Although it began as a Java development
environment, it has expanded through plugins. This IDE is managed and directed by the
Eclipse.org Consortium.
• NetBeans: Supports Java, PHP, JavaScript, C, C++, Python, Ruby, and more. It is also free
and open source. Modules provide all functions of the IDE. Developers can add support for
other programming languages by installing additional modules.
• Komodo IDE: Supports Perl, PHP, Python, Tcl, JavaScript, Ruby, and more. This is an
enterprise-level tool with a higher price point.

IDE for Mobile Development Processes

Specifically for mobile development, there are IDEs that include PhoneGap and Titanium Mobile
from Appcelerator.

A lot of IDEs, particularly multi-language IDEs, have mobile-development plugins. Eclipse, for
example, has this functionality.

HTML IDE

IDEs for developing HTML applications are some of the most popular IDEs around. For example,
DreamWeaver, HomeSite, and FrontPage automate numerous tasks involved in the process of
website development.

Cloud-Based IDE

Starting to become more mainstream, cloud-based IDEs are something to keep an eye on. The
capabilities of such web-based IDEs are growing rapidly; for that reason, most major vendors will
likely need to offer one if they want to stay competitive in their markets. Cloud IDEs are important
because they give programmers access to their code from anywhere.

For example, Nitrous is a cloud-based development environment platform that supports Ruby,
Python, Node.js and more. Cloud9 IDE supports more than 40 languages, including PHP, Ruby,
Python, JavaScript with Node.js, and Go. Heroku is a cloud-based development platform as a
service (PaaS), supporting several programming languages.
[4]

IDE That Are Specific to Apple or Microsoft

• Visual Studio: Supports VB.NET, Visual C++, C#, F# and more. Visual Studio is
Microsoft's IDE, designed to create apps for the Microsoft platform.
• MonoDevelop: Supports Visual Basic, C/C++, C#, and additional .NET languages.
• Xcode: Supports Swift and Objective-C languages, as well as Cocoa and Cocoa Touch
APIs. This IDE is solely for creating iOS and Mac applications. It includes a GUI builder
and an iPhone/iPad simulator.
• Espresso: Supports XML, HTML, CSS, PHP, and JavaScript. Espresso is a tool specifically
for Mac web programmers.
• Coda: Supports PHP, CSS, HTML, JavaScript, AppleScript, and Cocoa API. This IDE is
highlighted as "one-window development" for Mac users.

IDE Made for Certain Languages

There are specific IDEs that cater to programmers who work in one language. These include Jikes
and Jcreator for Java, CodeLite and C-Free for C/C++, RubyMine for Ruby/Rails, and Idle for
Python.

1.2.Install and configure PHP environment

Installing PHP on your computer allows you to safely develop and test a web application without
affecting the live system.

To work with PHP locally, you need to have the following software:

• PHP
• A web server that supports PHP. We’ll use the Apache webserver.
• A database server. We’ll use the MySQL database server.

Typically, you won’t install all this software separately because connecting them is tricky and not
intended for beginners.

Therefore, it’s easier to find an all-in-one software package that includes PHP, a web server, and a
database server. One of the most popular PHP development environments is XAMPP.

XAMPP is an easy install Apache distribution that contains PHP, MariaDB, and Apache webserver.
XAMPP supports Windows, Linux, and macOS.
[5]

1.3. Test the PHP environment

PHP Hello World

PHP Hello World on the web browser

First, open the folder htdocs under the xampp folder. Typically, it locates at C:\xampp\htdocs.

Second, create a new folder called helloworld.

Third, create a new file called index.php under the helloworld folder and place the following code
in the file:

The code in the index.php file looks like a regular HTML document except the part <?php and ?> .

The code between the opening tag <?php and closing tag ?> is PHP:

This PHP code prints out the Hello, World message inside the h1 tag using the echo statement:

When PHP executes the index.php file, it evaluates the code and returns the Hello, World!message.

Fourth, launch a web browser and open the URL:


[6]

If you see the following on the web browser, then you’ve successfully executed the first PHP script:

If you view the soure code of the page, you’ll see the following HTML code:

PHP Hello World on the command line

First, open the Command Prompt on Windows or Terminal on macOS or Linux.

Second, navigate to the folder c:\xampp\htdocs\helloworld\.

Third, type the following command to execute the index.php file:

You’ll see the HTML output.


[7]

Since the terminal doesn’t know how to render HTML to web, it just shows the pure HTML code.

To simplify the output, you can use the following code in the index.php:

Learning Unit 2: PHP Fundamentals

2.1.PHP Basic concepts, Output functions, data types and variables

PHP Syntax

As a programming language, PHP has a set of rules that governs how you write programs.

PHP code

Like HTML, you need to have the opening tag to start PHP code:

If you mix PHP code with HTML, you need to have the enclosing tag:

For example:
[8]

However, if a file contains only PHP code, the enclosing tag is optional:

Case sensitivity

PHP is partially case-sensitive. Knowing what are case sensitive and what is not is very important
to avoid syntax errors.

If you have a function such as count, you can use it as COUNT. It would work properly.

The following are case-insensitive in PHP:

• PHP constructs such as if, if-else, if-elseif, switch, while, do-while, etc.
• Keywords such as true and false.
• User-defined function & class names.

On the other hand, variables are case-sensitive. e.g., $message and $MESSAGE are different
variables.

Statements

A PHP script typically consists of one or more statements. A statement is a code that does
something, e.g., assigning a value to a variable and calling a function.
[9]

A statement always ends with a semicolon (;). The following shows a statement that assigns a literal
string to the $message variable:

PHP Variables

A variable stores a value of any type, e.g., a string, a number, an array, or an object.

A variable has a name and is associated with a value. To define a variable, you use the following
syntax:

When defining a variable, you need to follow these rules:

• The variable name must start with the dollar sign ($).
• The first character after the dollar sign ( $) must be a letter (a-z) or the underscore ( _ ).
• The remaining characters can be underscores, letters, or numbers.

PHP variables are case-sensitive. It means that $message and $Message variables are entirely
different.

The following example defines a variable called $title:

To display the values of variables on a webpage, you’ll use the echo construct. For example:
[10]

If you open the page, you’ll see the following message:

Another shorter way to show the value of a variable on a page is to use the following syntax:

For example, the following shows the value of the $title variable in the heading:
[11]

Mixing PHP code with HTML will make the code unmaintainable, especially when the application
grows. To avoid this, you can separate the code into separate files. For example:

• index.php – store the logic for defining and assigning value to variables.
• index.view.php – store the code that displays the variables.
• Use the require construct to include the code from the index.view.php in the index.phpfile.

The following shows the contents of the index.view.php file:


[12]

And the following shows the contents of the index.php file:

If you open the index.php file on the web browser, you’ll see the same output.

By doing this, you separate the code responsible for logic and the code responsible for displaying
the file. This is called the separation of concerns (SoC) in programming.

PHP Comments

Comments are important parts of the code. Comments provide useful information that will help you
and other developers understand the meaning of the code more quickly later.

PHP supports two types of comments:

• One-line comments
• Multi-line comments

One-line comments

The one-line comment is placed at the end of the line or at the current block.

A one-line comment starts with the pound (#) or double forward-slash (//). The rest of the text after
the (//) is ignored by the PHP interpreter.

The following example uses the // for a one-line comment:

And the following example uses the # for a one-line comment:


[13]

Multi-line comments

A Multi-line comment start with /* and end with */. For example:

Summary

• Comments are important parts of the code because they explain why code does what it is
supposed to do.
• PHP supports both one-line and multi-line comments.
• A one-line comment starts with the # or // .
• A multi-line comment starts with /* and end with */.

PHP Constants

Introduction to PHP constants

A constant is simply a name that holds a single value. As its name implies, the value of a constant
cannot be changed during the execution of the PHP script.

To define a constant, you use the define() function. The define() function takes the constant’s
name as the first argument and the constant value as the second argument. For example:
[14]

By convention, constant names are uppercase. Unlike a variable, the constant name doesn’t start
with the dollar sign($).

By default, constant names are case-sensitive. It means that WIDTH and width are different
constants.

In PHP 5, a constant can hold a simple value like a number, a string, a boolean value. From PHP
7.0, a constant can hold an array. For example:

The const keyword

PHP provides you with another way to define a constant via the const keyword. Here’s the syntax:

In this syntax, you define the constant name after the const keyword. To assign a value to a
constant, you use the assignment operator (=) and the constant value. The constant value can be
scalar, e.g., a number, a string, or an array.

The following example uses the const keyword to define the SALES_TAX constant:
[15]

PHP Data Types

A type specifies the amount of memory that allocates to a value associated with it. A type also
determines the operations that you can perform on it.

PHP has ten primitive types including four scala types, four compound types, and two special types:

Scalar types

A variable is a scalar when it holds a single value of the type integer, float, string, or boolean.

Integer

Integers are whole numbers defined in the set {…-3,-2-,-1,0,1,2,3…}. The size of the integer
depends on the platform where PHP runs.

The constant PHP_INT_SIZE specifies the size of the integer on a specific platform. PHP uses the
int keyword to denote the integer type.

The following example illustrates some integers:


[16]

Float

Floats are floating-point numbers, which are also known as floats, doubles, or real numbers.

PHP uses the float keyword to represent the floating-point numbers. The following example
illustrates the floating-point numbers in PHP:

Boolean

Boolean represents a truth value that can be either true or false. PHP uses the bool keyword to
represent the Boolean type.

The bool type has two values true and false. Since keywords are case-insensitive, you can
use true, True, TRUE, false, False, and False to indicate boolean values.

The following example shows how to assign Boolean values to variables:


[17]

String

A string is a sequence of characters surrounded by single quotes (‘) or double quotes (“). For
example:

2.2. PHP Operators

An operator takes one or more values, known as operands, and performs a specific operation on
them.

For example, the + operator adds two numbers and returns the sum of them.

PHP supports many kinds of operators:

• Arithmetic Operators
• Assignment Operators
• Bitwise Operators
• Comparison Operators
• Increment/Decrement Operators
• Logical Operators
• Concatenating Operators
• Arithmetic Operators
• The arithmetic operators require numeric values. If you apply them to non-numeric values,
they’ll convert them to numeric values before carrying the arithmetic operation.
• The following are the list of arithmetic operators:
[18]

Operator Name Description

+ Addition Return the sum of two operands

– Subtraction Return the difference between two operands

* Multiplication Return the product of two operands

/ Division Return the quotient of two operands

% Modulus Return the remainder of the division of the first operand by the
second one

The following example uses the arithmetic operators:


[19]

Comparison Operators

Comparison operators allow you to compare two operands.

A comparison operator returns a Boolean value, either true or false. If the comparison is truthful,
the comparison operator returns true, otherwise, it returns false.

The following are the list of comparison operators in PHP:

Operator Name Description

== Equality Return true if both operands are equal, otherwise returns false.

=== Identity Return true if both operands have the same data type and equal, otherwise
return false.

!=== Not identical Return true if both operands are not equal or not have the same data type,
otherwise returnfalse.

> Greater than Return true if the operand on the left is greater than the operand on the right,
otherwise return false.
[20]

Operator Name Description

>= Greater than or Return true if the operand on the left is greater than or equal to the operand on
equal to the right, otherwise return false.

< Less than Return true if the operand on the left is less than the operand on the right,
otherwise return false.

<= Less than or equal Return true if the operand on the left is less than or equal to the operand on the
right, otherwise return false.

Logical Operators

Logical operators allow you to construct logical expressions. A logical operator returns a Boolean
value.

PHP provides the following logical operators:

Operator Name Description

&& Logical Return true if both operands are true, otherwise return false. If the first operand is false, it
AND will not evaluate the second operand because it knows for sure that the result is going to
be false. This is known as short-circuiting.

|| Logical Return true if one of the operands is true, otherwise returns false. If the first operand
OR is true, it will not evaluate the second one.

xor Logical Return true if either operand, not both, is true, otherwise, return false.
XOR

! Not returns true if the operand is false, and returns false if the operand is true.

Bitwise Operators
[21]

Bitwise operators perform operations on the binary representation of the operands. The following
illustrates bitwise operators in PHP:

Operators Name Result

$x & $y And If both bits are 1, the corresponding bit in the result is 1; otherwise, the
corresponding bit is 0

$x | $y Or (inclusive If both bits are 0, the corresponding bit in the result is 0; otherwise, the
or) corresponding bit is 1

$x ^ $y Xor (exclusive If either bit, but not both, in $x and $y are 1, the corresponding bit in the result is 1;
or) otherwise, the corresponding bit is 0

~ $x Not Change bit 1 to 0 and 0 to 1 in the $x operand

$x << $y Shift left Shifts the bits in $x left by the number of places specified by $y.

$x >> $y Shift right Shifts the bits in $x right by the number of places specified by $y.

Incrementing/ Decrementing Operators

Increment (++) and decrement (–) operators give you a quick way to increase and decrease the
value of a variable by 1.

The following table illustrates the increment and decrement operators:

Example Name Returned Value Effect on $a

++$a Pre-increment $a + 1 Increments $a by 1, then returns $a.

$a++ Post-increment $a Returns $a, then increments $a by 1.

--$a Pre-decrement $a – 1 Decrements $a by 1, then returns $a.


[22]

Example Name Returned Value Effect on $a

$a-- Post-decrement $a Returns $a, then decrements $a by 1.

Concatenating Operator

Concatenating operator (.) allows you to combine two strings into one. It appends the second string
to the first one and returns the combined string. For example:

Assignment Operators

Assignment operator ( =) assigns a value to a variable and returns a value. The operand on the left is
always a variable, while the operand on the right can be a literal value, variable, expression, or a
function call that returns a value. For example:

In the first expression, we assigned $x variable value 10. In the second one, we assigned the value
of $x to $y variable. The third one is a little bit complicated. First, we assigned 20 to $x. The
assignment operator (=) returns 20 and then 20 is assigned to $z variable.

Besides the basic assignment operator (=), PHP provides you with some assignment operators:

• plus-equal +=
• minus-equal -=
• divide-equal /=
[23]

• multiplication-equal *=
• modulus-equal %=
• XOR-equal ^=
• AND-equal &=
• OR-equal |=
• concatenate-equal .=

PHP operators precedence

The precedence of an operator decides which order the operator is evaluated in an expression.

PHP assigned each operator precedence. Some operators have the same precedence, e.g.,
precedences of the addition ( +) and subtraction( -) are equal.

However, some operators have higher precedence than others.

For example, the precedence of the multiplication operator ( *) is higher than the precedence of the
add( +) and the subtract ( -) operators:

Because the precedence of the multiplication operator ( *) is higher than the precedence of the
add( +) operator, PHP evaluates the multiplication operator ( *) first and then add operator ( *)
second.

To force the evaluation in a particular order, you put the expression inside parentheses (), for
example:

PHP assignment operator


[24]

PHP uses the = to represent the assignment operator. The following shows the syntax of the
assignment operator:

On the left side of the assignment operator (=) is a variable to which you want to assign a value.
And on the right side of the assignment operator (=) is a value or an expression.

When evaluating the assignment operator (=), PHP evaluates the expression on the right side first
and assigns the result to the variable on the left side. For example:

In this example, we assigned 10 to $x, 20 to $y, and the sum of $x and $y to $total.

The assignment expression returns a value assigned, which is the result of the expression in this
case:

It means that you can use multiple assignment operators in a single statement like this:

In this case, PHP evaluates the right-most expression first:

The variable $y is 20.


[25]

The assignment expression $y = 20 returns 20 so PHP assigns 20 to $x. After the assignments,
both $x and $y equal 20.

Arithmetic assignment operators

Sometimes, you want to increase a variable by a specific value. For example:

How it works.

• First, $counter is set to 1.


• Then, increase the $counter by 1 and assign the result to the $counter.

After the assignments, the value of $counter is 2.

PHP provides the arithmetic assignment operator += that can do the same but with a shorter code.
For example:

The expression $counter += 1 is equivalent to the expression $counter = $counter + 1.

Besides the += operator, PHP provides other arithmetic assignment operators. The following table
illustrates all the arithmetic assignment operators:

Operator Example Equivalent Operation

+= $x += $y $x = $x + $y Addition

-= $x -= $y $x = $x – $y Subtraction
[26]

Operator Example Equivalent Operation

*= $x *= $y $x = $x * $y Multiplication

/= $x /= $y $x = $x / $y Division

%= $x %= $y $x = $x % $y Modulus

**= $z **= $y $x = $x ** $y Exponentiation

PHP comparison operators

A comparison operator allows you to compare two values and returns true if the comparison is
truthful and false otherwise.

The following table illustrates the comparison operators in PHP:

Operator Name Description

== Equal to Return true if both operands are equal; otherwise, it returns false.

!=, <> Not equal to Return true if both operands are equal; otherwise, it returns false.

=== Identical to Return true if both operands have the same data type and equal; otherwise, it
returns false.

!== Not identical to Return true if both operands are not equal or not have the same data type;
otherwise, it returns false.

> Greater than Return true if the operand on the left is greater than the operand on the right;
otherwise, it returns false.
[27]

Operator Name Description

>= Greater than or Return true if the operand on the left is greater than or equal to the operand on
equal to the right; otherwise, it returns false.

< Less than Return true if the operand on the left is less than the operand on the right;
otherwise, it returns false.

<= Less than or equal Return true if the operand on the left is less than or equal to the operand on the
to right; otherwise, it returns false.

Equality Operator (==)

The equality returns true if both values are equal; otherwise, it returns false. The following example
returns true because 10 is equal 10:

The following example returns false because 10 is not equal 20:

If you want to compare two values with the consideration of type, you can use the identical operator
(===).
[28]

Not equal to operator (!=, <>)

The not equal to (!=, <>) operator returns true if the lefthand value is not equal to the righthand
value; otherwise, it returns false. For example:

Greater than (>)

The greater than return true if the lefthand value is greater than the righthand value; otherwise, it
returns false:

Greater than or equal to (>=)

The greater than or equal to operator returns true if the lefthand value is greater than or equal to the
righthand value; otherwise, it returns false. For example:
[29]

Less than (<)

The less than operator returns true if the lefthand value is less than the righthand value; otherwise, it
returns false. For example:

Less than or equal to (<=)

If the lefthand value is less than or equal to the righthand value, the less than or equal to operator
returns true; otherwise, it returns false. For example:
[30]

PHP AND operator

The logical AND operator accepts two operands and returns true if both operands are true;
otherwise, it returns false.

PHP uses the and keyword to represent the logical AND operator:

The following table illustrates the result of the and operator:

expression1 expression2 expression1 and expression2

true true True

true false False

false true False

false false False

In addition to using the and keyword, PHP uses && as the logical AND operator:

The && and and operators return the same result. The only difference between
the && and andoperators are their precedences.

The and operator has higher precedence than the && operator. The precedence of an operator
specifies the order in which PHP evaluates.

PHP OR operator
[31]

he logical OR operator accepts two operands and returns true if either operand is true; otherwise, it
returns false. In other words, the logical OR operator returns false if both operands are false.

To represent the logical OR operator, PHP uses either the or keyword or the || as follows:

Or

The following table illustrates the result of the or operator:

expression1 expression2 expression1 || expression2

true true True

true false True

false true True

false false False

Note that the or, Or, and OR are the same because PHP keywords are case-insensitive.

The || and or operators return the same result. The only difference between the || and oroperators are
their precedences. The or operator has higher precedence than the || operator.

2.3. PHP control structure


2.3.1. PHP Conditional Statement

Conditional statements are used to perform different actions based on different conditions. In PHP
we have the following conditional statements:
[32]

• 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

PHP If statement

The if statement allows you to execute a statement if an expression evaluates to true.

Syntax:

if (condition) {
code to be executed if condition is true;
}

Example: A program that add 10 to student marks bellow 20

<?php
$mark = 15;

if ($mark < 20) {


echo $mark += 10;
}
?>

PHP if else

if...else statement that executes a code block when a condition is true or another code block when
the condition is false.

Syntax:

if (condition) {
code to be executed if condition is true;
} else {
code to be executed if condition is false;
}

Example: A program that check whether a number is Odd or Even

<?php
$t = 4;
[33]

if ($t%2 == 0) {
echo $t": is Even number";
} else {
echo $t": is Even number";
}
?>

PHP If elseif else statement

The if....elseif...else statement executes different codes for more than two conditions.

Syntax:

if (condition) {
code to be executed if this condition is true;
} elseif (condition) {
code to be executed if this condition is true;
} else {
code to be executed if all conditions are false;
}

Example: a program that compare two numbers.

<?php
$x = 20;

$y = 30;

if ($x > $y) {


echo "x is a greatest number";
} elseif ($y > $x) {
echo "y is a greatest number";
} else {
echo "x and y are equal";
}
?>

PHP Switch statement

Use the switch statement to select one of many blocks of code to be executed.
[34]

Syntax:

switch (n) {
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
break;
case label3:
code to be executed if n=label3;
break;
...
default:
code to be executed if n is different from all labels;
}

First, we have a single expression n (most often a variable), that is evaluated once. The value of the
expression is then compared with the values for each case in the structure. If there is a match, the
block of code associated with that case is executed. Use break to prevent the code from running
into the next case automatically. The default statement is used if no match is found.

<?php
$favcolor = "red";

switch ($favcolor) {
case "red":
echo "Your favorite color is red!";
break;
case "blue":
echo "Your favorite color is blue!";
break;
case "green":
echo "Your favorite color is green!";
break;
default:
echo "Your favorite color is neither red, blue, nor green!";
}
?>

2.3.2. PHP Loops

Often when you write code, you want the same block of code to run over and over again a certain
number of times. So, instead of adding several almost equal code-lines in a script, we can use loops.
[35]

Loops are used to execute the same block of code again and again, as long as a certain condition is
true. In PHP, we have the following loop types:

• while - loops through a block of code as long as the specified condition is true
• do...while - loops through a block of code once, and then repeats the loop as long as the
specified condition is true
• for - loops through a block of code a specified number of times
• foreach - loops through a block of code for each element in an array

PHP While loop

The while loop executes a block of code as long as the specified condition is true.

Syntax:

while (condition) {
code to be executed;
}

Example:

<?php
$x = 1;
while($x <= 5) {
echo "The number is: $x <br>";
$x++;
}
?>

PHP do...while Loop


The do...while loop 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);

The example below first sets a variable $x to 1 ($x = 1). Then, the do while loop will write some
output, and then increment the variable $x with 1. Then the condition is checked (is $x less than, or
equal to 5?), and the loop will continue to run as long as $x is less than, or equal to 5:
[36]

Example:

<?php
$x = 1;

do {
echo "The number is: $x <br>";
$x++;
} while ($x <= 5);
?>

PHP for Loop


The for loop is used when you know in advance how many times the script should run.

Syntax:

for (initialize counter; test counter; increment counter) {


code to be executed;
}

Parameters:

• init counter: Initialize the loop counter value


• test counter: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues.
If it evaluates to FALSE, the loop ends.
• increment counter: Increases the loop counter value

Example:

<?php
for ($x = 0; $x <= 10; $x++) {
echo "The number is: $x <br>";
}
?>

PHP foreach Loop


The foreach loop works only on arrays, and is used to loop through each key/value pair in an array.

Syntax:

foreach ($array as $value) {


code to be executed;
}
[37]

Example:

For every loop iteration, the value of the current array element is assigned to $value and the array
pointer is moved by one, until it reaches the last array element.

The following example demonstrates a loop that will output the values of the given array ($colors):

<?php
$colors = array("red", "green", "blue", "yellow");

foreach ($colors as $value) {


echo "$value <br>";
}
?>

2.4. PHP Arrays


2.4.1. Definition of PHP Array

An array is a special variable, which can hold more than one value at a time.

2.4.2. Creating PHP Array

In PHP, the array() function is used to create an array:

array();

2.4.3. Different types of arrays

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

PHP Indexed Arrays

There are two ways to create indexed arrays:

The index can be assigned automatically (index always starts at 0), like this:

$cars = array("Volvo", "BMW", "Toyota");


or the index can be assigned manually:
$cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota";
[38]

PHP Associative Arrays


Associative arrays are arrays that use named keys that you assign to them.

There are two ways to create an associative array:

$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");

or:

$age['Peter'] = "35";
$age['Ben'] = "37";
$age['Joe'] = "43";

Multidimensional Arrays

A multidimensional array is an array containing one or more arrays.

PHP supports 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.

The dimension of an array indicates the number of indices you need to select an element.

• 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

Two-dimensional Arrays

A two-dimensional array is an array of arrays (a three-dimensional array is an array of arrays of


arrays).

First, take a look at the following table:

Name Stock Sold

Volvo 22 18

BMW 15 13

Land Rover 17 15

We can store the data from the table above in a two-dimensional array, like this:
[39]

$cars = array (
array("Volvo",22,18),
array("BMW",15,13),
array("Land Rover",17,15)
);
Example:
<?php
echo $cars[0][0].": In stock: ".$cars[0][1].", sold: ".$cars[0][2].".<br>";
echo $cars[1][0].": In stock: ".$cars[1][1].", sold: ".$cars[1][2].".<br>";
echo $cars[2][0].": In stock: ".$cars[2][1].", sold: ".$cars[2][2].".<br>";
echo $cars[3][0].": In stock: ".$cars[3][1].", sold: ".$cars[3][2].".<br>";
?>
We can also put a for loop inside another for loop to get the elements of the $cars array (we still
have to point to the two indices):

<?php
for ($row = 0; $row < 4; $row++) {
echo "<p><b>Row number $row</b></p>";
echo "<ul>";
for ($col = 0; $col < 3; $col++) {
echo "<li>".$cars[$row][$col]."</li>";
}
echo "</ul>";
}
?>

PHP Sorting Arrays


The elements in an array can be sorted in alphabetical or numerical order, descending or ascending.
we will go through the following PHP array sort functions:

• sort() - sort arrays in ascending order


• rsort() - sort arrays in descending order
• asort() - sort associative arrays in ascending order, according to the
value
• ksort() - sort associative arrays in ascending order, according to the
key
• arsort() - sort associative arrays in descending order, according to
the value
• krsort() - sort associative arrays in descending order, according to
the key
[40]

2.5.PHP functions

PHP function is a piece of code that can be reused many times. It can take input as argument list
and return value. There are thousands of built-in functions in PHP.
PHP Built-in Functions

PHP has over 1000 built-in functions that can be called directly, from within a script, to perform a
specific task.

Please check out our PHP reference for a complete overview of the PHP built-in functions.

Besides the built-in PHP functions, it is possible to create your own functions.

• A function is a block of statements that can be used repeatedly in a program.


• A function will not execute automatically when a page loads.
• A function will be executed by a call to the function.

Create a User Defined Function in PHP


A user-defined function declaration starts with the word function:
Syntax
function functionName() {
code to be executed;
}
Example:

<html>

<head>
<title>Writing PHP Function</title>
</head>

<body>

<?php
/* Defining a PHP Function */
function writeMessage() {
echo "You are really a nice person, Have a nice time!";
}

/* Calling a PHP Function */


writeMessage();
?>
</body>
</html>

PHP Function Arguments

Information can be passed to functions through arguments. An argument is just like a variable.
[41]

Arguments are specified after the function name, inside the parentheses. You can add as many
arguments as you want, just separate them with a comma.

We can pass the information in PHP function through arguments which is separated by comma.

PHP supports Call by Value (default), Call by Reference, Default argument values and Variable-
length argument list.

<html>

<head>
<title>Writing PHP Function with Parameters</title>
</head>

<body>

<?php
function addFunction($num1, $num2) {
$sum = $num1 + $num2;
echo "Sum of the two numbers is : $sum";
}

addFunction(10, 20);
?>

</body>
</html>

PHP Call By Reference

Value passed to the function doesn't modify the actual value by default (call by value). But we can
do so by passing value as a reference.

By default, value passed to the function is call by value. To pass value as a reference, you need to use
ampersand (&) symbol before the argument name.

<?php
function adder(&$str2)
{
$str2 .= 'Call By Reference';
}
$str = 'Hello ';
adder($str);
echo $str;
?>
Example:
[42]

<html>

<head>
<title>Passing Argument by Reference</title>
</head>

<body>

<?php
function addFive($num) {
$num += 5;
}

function addSix(&$num) {
$num += 6;
}

$orignum = 10;
addFive( $orignum );

echo "Original Value is $orignum<br />";

addSix( $orignum );
echo "Original Value is $orignum<br />";
?>

</body>
</html>

PHP Function: Returning Value

A function can return a value using the return statement in conjunction with a value or object.
return stops the execution of the function and sends the value back to the calling code.

html>

<head>
<title>Writing PHP Function which returns value</title>
</head>

<body>

<?php
function addFunction($num1, $num2) {
$sum = $num1 + $num2;
return $sum;
}
$return_value = addFunction(10, 20);

echo "Returned value from the function : $return_value";


?>
[43]

</body>
</html>

2.6. PHP Sessions

A session is a way to store information (in variables) to be used across multiple pages.
Importance of PHP Session
1. Limit the number of logins
For instance if your application should allow only 10 logins at a time , then the session table
can be checked to find the number of users already logged in. If the limit is exceeded, then
further users may not be allowed to log in.
2. Block multiple logins for same username.
If your website or application needs to make a user login from only 1 location at a time for
security purpose or something else , then the sessions table can simply delete the earlier
session data of a particular username and login the new one.
3. Monitor user activity
View which user is currently online, when did he login and for how long has he been active.
4. Logout a user
A user can be logged out simply by removing his session entry in the database. This can be
useful to logout users who have been inactive for a long time
Where to apply PHP session
Starting a PHP Session
It is recommended to put the call to session_start () at the beginning of the page. Session
variables are stored in associative array called $_SESSION[]. These variables can be accessed
during lifetime of a session.
CREATING PHP SESSION USING ISSET()

PHP isset() Function


The isset() function checks whether a variable is set, which means that it has to be declared
and is not NULL. This function returns true if the variable exists and is not NULL, otherwise it
returns false.
Example 1:

<?php
session_start();
if(isset($_SESSION['views']))
$_SESSION['views'] = $_SESSION['views']+ 1;
else
$_SESSION['views'] = 1;

echo "views = ". $_SESSION['views'];


?>
[44]

Example 2:

<? php
session_start();

if( isset( $_SESSION['counter'] ) ) {


$_SESSION['counter'] += 1;
}else {
$_SESSION['counter'] = 1;
}

$ msg = "You have visited this page ". $_SESSION['counter'];


$ msg .= "in this session.";
?>

<html>

<head>
<title> PHP session</title>
</head>

<body>
<?php echo ( $msg ); ?>
</body>

</html>

CREATING PHP SESSION STARTING A PHP SESSION

<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
// Set session variables
$_SESSION ["favcolor"] = "green";
$_SESSION ["favanimal"] = "cat";
echo "Session variables are set.";
?>

</body>
</html>

PHP VARIABLES
[45]

Variables are "containers" for storing information.

<? PHP
$txt = "Hello world!";
$x = 5;
$y = 10.5;
?>
MODIFYING PHP SESSION VARIABLE

<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
// to change a session variable, just overwrite it
$_SESSION["favcolor"] = "yellow";
print_r($_SESSION);
?>

</body>
</html>

DESTROYING PHP SESSION

A PHP session can be destroyed by session_destroy() function. This function does not need
any argument and a single call can destroy all the session variables. If you want to destroy a
single session variable then you can use unset() function to unset a session variable.
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// remove all session variables
session_unset();

// destroy the session


session_destroy();
?>

</body>
</html>
[46]

2.7. PHP RegEx

A regular expression is a sequence of characters that forms a search pattern. When you search for
data in a text, you can use this search pattern to describe what you are searching for.

PHP provides a variety of functions that allow you to use regular expressions. The preg_match(),
preg_match_all() and preg_replace()functions are some of the most commonly used ones:

Function Description

preg_match() Returns 1 if the pattern was found in the string and 0 if not

preg_match_all() Returns the number of times the pattern was found in the string, which may also
be 0

preg_replace() Returns a new string where matched patterns have been replaced with another
string

PHP string functions allow you to test if a string contains a substring (str_contains()) or to replace
all occurrences of a substring with another string (str_replace()).

However, these functions deal with fixed patterns. They won’t work with flexible patterns. For
example, if you want to search any numbers in a string, the str_contains() won’t work.

A regular expression is a string that describes a pattern such as phone numbers, credit card numbers,
and email addresses.

Create regular expressions

To create a regular expression, you place a pattern in forward-slashes like this:

For example:
[47]

The $pattern is a string. Also, it is a regular expression that matches a number with one or more
digits. For example, it matches the numbers 1, 20, 300, etc.

Note that you’ll learn how to form flexible regular expressions in the following tutorial.

The forward-slashes are delimiters. The delimiters can be one of the following characters ~, !, @, #,
$ or braces including {}, (), [], <>. The braces help improve regular expressions’ readability in
some cases. Note that you cannot use the alphanumeric, multi-byte, and backslashes (\) as
delimiters.

The following regular expression uses the curly braces as delimiters:

Search strings using regular expressions to search a string for a match to a pattern, you use the
preg_match() and preg_match_all()functions.

PHP preg_match() function

To search based on a regular expression, you use the preg_match() function. For example:

Output:
[48]

The preg_match() searches the $message for a match to the $pattern. The preg_match() function
returns 1 if there is a match in the $message, 0 if it doesn’t, or false on failure.

To get the text that matches the pattern, you add the third parameter to the preg_match() function
like the following example:

Output:

The $matches parameter contains all the matches. The $matches[0] stores the text that matches the
pattern. In this example, it is the number 8.

The $matches[1], $matches[2], ….. store the texts that match the first, second,…. The preg_match()
only returns the first match and stops searching as soon as it finds the first one. To find all matches,
you use the preg_match_all() function.

PHP preg_match_all() function

The preg_match_all() function searches for all matches to a regular expression. For example:
[49]

Output:

In this example, the preg_match_all() puts all matches in a multidimensional array with the first
element contains the texts (8, 26 and 2020) that match the pattern.

The preg_match_all() function returns the number of matches, which can be zero or a positive
number.

Replace strings using regular expressions

To replace strings that match a regular expression, you use the preg_replace() function. For
example:
[50]

Output:

In this example, the preg_replace() function replaces all numbers in the $message with the
string %d.

2.8.Form handling

To create a form, you use the <form> element as follows:

The <form> element has two important attributes:

➢ Action: specifies the URL that processes the form submission. In this example, the
form.php will process the form.
➢ method: : specifies the HTTP method for submitting the form. The most commonly used
form methods are POST and GET. In this example, the form method is post.

In this example, the form method is post or POST . If you don’t specify the method attribute, the
form element will use the get method by default.

Typically, a form has one or more input elements including text, password, checkbox, radio
button, select, file upload, etc. The input elements are often called form fields.

An input element has the following important attributes

Typically, a form has one or more input elements including text, password, checkbox, radio
button, select, file upload, etc. The input elements are often called form fields.

An input element has the following important attributes name, type and value. The name attribute
will be used for accessing the value in PHP.

HTTP POST method

If a form uses the POST method, the web browser will include the form data in the HTTP request’s
body. After submitting the form, you can access the form data via the associative array $_POST in
PHP.

For example, if a form has an input element with the name email, you can access the email value in
PHP via the $_POST['email'] . If the form doesn’t have an email input, the $_POST won’t have any
element with the key 'email'.
[51]

To check if the form data contains the email, you use the isset() like this:

The following shows a form with an input element:

In the form.php file, you can access the email value as follows:

HTTP GET method

When you submit a form using the GET method, you can access the form data in PHP via the
associative array $_GET. Unlike the POST method, the GET method appends the form data in the
URL that processes the form. Suppose the URL that processes the form is http://localhost/form.php
and submit a form, you’ll see that the email value is appended to the URL.

In PHP, you can use the isset() to check if the form data contains the email:
[52]

If the form has multiple input elements, the web browser will append the form inputs to the URL in
the following format:

The following shows the same form that has an email input. However, the form uses the GET
method instead:

And the following shows the form.php file:

Note that both $_POST and $_GET arrays are superglobal variables. It means that you can access
them anywhere in the script.

HTTP GET or POST

In general, you should use the GET method when the form only retrieves data from the server. For
example, a search form that allows users to search for information should use the GET method.

When you have a form that causes a change in the server, you should use the POST method. For
example, a form that allows users to subscribe to a newsletter should use the POST method.
[53]

PHP form example

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-
scale=1.0" />
<link rel="stylesheet" href="css/style.css">
<title>PHP Form</title>
</head>
<body>
<main>
<form action="subscribe.php" method="post">
<div>
<label for="name">Name:</label>
<input type="text" name="name" required="required"
placeholder="Enter your name" />
</div>

<div>
<label for="name">Email:</label>
<input type="email" name="email" required="required"
placeholder="Enter your email" />
</div>

<button type="submit">Subscribe</button>
</form>
</main>
</body>

</html>

The form uses the POST method and submits the data to the subscribe.php page. It has two input
elements with type text and email.

Before submitting the form to the server, the web browser checks if all required fields are filled out,
in the correct format. This is known as client-side form validation.

To validate data on the client-side, you can use either HTML5 form validation or JavaScript
validation. However, you should never rely on client-side validation as a security measure.

The client-side validation’s purpose is to help legitimate users to enter data in the correct format.
However, it doesn’t prevent malicious users from entering bad data that potentially harm the
application. Therefore, it’s mandatory to implement server-side validation.

The following shows the code of the subscribe.php file:


[54]

How it works.

• First, check if the name and email are in the $_POST array using the isset() function.
• Second, show a thank you message.

PHP self-processing form

Sometimes, you want to include both form and logic for handling form submission in a single PHP
file. This form is often referred to as a self-processing form.

To create a self-processing form, you can use the $_SERVER['REQUEST_METHOD'] that returns
the request method e.g., GET or POST.

If the $_SERVER['REQUEST_METHOD'] is GET, you show the form. And if


the $_SERVER['REQUEST_METHOD'] is POST, you process it. For example:
[55]
[56]

However, mixing PHP & HTML is not always a good practice.

To make the code more organized, you can create the following file & directory structure:

The index.php file in the root directory will include the header.php and footer.php.

If the request method is GET , the index.php file loads the form in the get.php file. Otherwise, it
loads the code from the post.php file for processing the POST request.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy