0% found this document useful (0 votes)
10 views

PHP CSC 208

PHP is a free, server-side scripting language that allows for dynamic content on web pages and is relatively easy to learn. The document provides an introduction to PHP, covering its requirements, syntax, and basic programming concepts such as variables, conditions, and loops. It also includes instructions for setting up a local server environment using XAMPP and creating PHP files.

Uploaded by

olasileagesin09
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

PHP CSC 208

PHP is a free, server-side scripting language that allows for dynamic content on web pages and is relatively easy to learn. The document provides an introduction to PHP, covering its requirements, syntax, and basic programming concepts such as variables, conditions, and loops. It also includes instructions for setting up a local server environment using XAMPP and creating PHP files.

Uploaded by

olasileagesin09
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 37

PHP

PHP is a free server-side scripting language that can add dynamic content to a webpage. Why
learn it? PHP is a simple language that can be learned quickly and can prepare you for other
programming languages as well as provide you with useful problem-solving skills.

Chapter 1 - Introduction to PHP

What is PHP?

PHP Requirements

How to Create A PHP File

Chapter 2 - PHP Syntax

Opening/Closing PHP Tags

PHP Instruction Termination

PHP Comments

PHP Whitespace

Chapter 3 - PHP Basics

PHP Variables

Output Statement

PHP Strings

PHP Operators

Chapter 4 - PHP Conditions & Loops

If

Else

Elseif

Switch

While

Do-While

For

Breaking Out of Loops

1
UNIT 1 – INTRODUCTION TO PHP

What is PHP?

PHP is a free open-source software already installed on many web servers today. PHP stands
for "PHP: Hypertext Preprocessor". It is a recursive acronym. It was originally named
Personal Home Page, and many people still think that’s what the acronym stands for. But as
it expanded in scope, a new and more appropriate (albeit GNU-ishly recursive) name was
selected by community vote. PHP is a server-side scripting language, which can be embedded
in HTML. Proprietary products in this niche are Microsoft’s Active Server Pages,
Macromedia’s ColdFusion, and Sun’s Java Server Pages.

PHP is a widely used server-side scripting language intended for use in web pages to create
dynamic content. PHP runs on a web server, which interprets the PHP scripts behind the
scenes and sends the results to the client. The client may not even know that a script was used
to produce the contents of the webpage that they are viewing.

What can PHP do?

Although PHP is a simple language, it comes with an extensive list of features that allows it
to be used in thousands of different ways to enhance websites and web applications. These
uses include, but are by no means limited to:

Solving Math Problems


Displaying Current Dates & Times
Handling Form Data
Sending & Receiving Cookies
Collecting Information About Your Website's Visitors
Performing CRUD Operations
Creating/Modifying Images
Creating Shopping Carts
Interacting with a Secure 3rd Party to Pay for Online Merchandise

Why PHP? Features of PHP:


1. Cross platform compatibility: PHP and MySQL run native on every popular flavour
of Unix (including Mac OS X) and Windows. A huge percentage of the world’s
HTTP servers run on one of these two classes of operating systems. PHP is
compatible with the three leading Web servers: Apache HTTP Server for Unix and
Windows, Microsoft Internet Information Server, and Netscape Enterprise Server
(a.k.a. IPlanet Server). It also works with several lesser-known servers, including
Microsoft’s Personal Web Server, AOL Server, and Omni Centrix’s Omni server
application server.

2. Not tag-based: PHP is a real programming language. ColdFusion, by contrast, is a


bunch of predefined tags, like HTML. In PHP, you can define functions to your
heart’s content just by typing a name and a definition. In ColdFusion, you must use
tags developed by other people or go through the Custom Tag Extension development
process.

3. Stability: Apache Server (included in WampServer) is generally considered the most


stable of major Web application servers, with a reputation for enviable uptime
percentages. Although it is neither the fastest nor the easiest to administer, once you
2
get it set up, Apache HTTP Server seemingly never crashes. It also doesn’t require
server reboots every time a setting is changed (at least on the Unix side). PHP inherits
this reliability; plus, its own implementation is solid yet lightweight.

4. Speed: PHP is pleasingly zippy in its execution, especially when compiled as an


Apache module on the Unix side. The MySQL server, once started, executes even
very complex queries with huge result sets in record-setting time. PHP5 is much faster
for almost every use than CGI scripts.
5. Open-source licensing: PHP is open-source software. The most immediate pragmatic
advantage is that you can compile your PHP installation with only the stuff you really
need for any given situation. This approach has performance and security advantages.
For instance, you can put in hooks to the database(s) of your choice. You can
recompile as often as you want: maybe when an Apache security release comes out,
or when you wish to support a new database application.
6. Many extensions: PHP makes it easy to communicate with other programs and
protocols. The PHP development team seems committed to providing maximum
flexibility to the largest number of users. Database connectivity is especially strong,
with native-driver support for about 15 of the most popular databases plus ODBC.
7. Popularity: PHP is fast becoming one of the most popular choices for so-called two-
tier development (Web plus data).
8. Strong user communities: PHP is developed and supported in a collaborative
fashion by a worldwide community of users. The main advantage for most new users
is technical support without charge, without boundaries, and without the runaround.
People on the mailing list are available 24/7/365 to answer your questions, help debug
your code, and listen to your gripes. The support is human and real. PHP community
members might tell you to read the manual, take your question over to the appropriate
database mailing list, or just stop your whining—but they’ll never tell you to wipe
your C drive and then charge you for the privilege.

PHP Requirements

Since it is safe to assume that you have access to a browser, a computer, an electrical socket
to plug in your computer, and a power plant to generate the power available to your electrical
socket, then the only remaining requirement to run PHP are the following three software
packages:

i. PHP engine: process the instructions in the script (which may access a database) and return the
script output to the browser to output as plain HTML.

ii. Web server: handles requests from web browsers. Basically, there are two types of requests made
to a webserver: the first asks for a file-often a static HTML web page or an image-to be returned, and
the second asks for a program or script to be run and its output to be returned.

iii. Database: A database is a collection related data stored in tables. A database server searches and
manages data stored in databases.

Each component mentioned above can be installed separately or can be gotten in a single package that
provide a local server environment that enables web developers to create and test their programs.
Single packages offered by PHP includes:

-WAMP (Windows Apache MySQL PHP)

-LAMP (Linux Apache MySQL PHP)


3
-MAMP (Mac OS Apache MySQL PHP)

-XAMPP (Cross platform Apache MySQL PHP)

Installing XAMPP: Xampp is an example of a web application server that allows you to
process PHP web pages. Once you have installed a Xampp on your system, you can then start
designing and testing your web site that uses PHP & MySql server technologies. Installing
Xampp is straightforward and simple. The following steps can be used to download and
install xampp on your computer.

Downloading xampp Server

1. Go to XAMPP's download page at https://apachefriends.org/


2. Select the version for your operating system (Windows, Linux, Mac).
3. Click the download link and save the installer.

Installing XAMPP
1. Run the XAMPP installer.
2. Click ‘Next’ to go through the setup wizard.
3. Choose the components you want to install (leave default selections checked).
4. Select the installation directory (default is usually fine).
5. Click ‘Next’ and then ‘Install’.
6. Once the installation is complete, open the XAMPP Control Panel.

Configuring and Running Your First PHP Script

1. Open the XAMPP


2. Click ‘Start’ next to Apache and MySQL.
3. The status lights should turn green.

It should be noted that, any web site that uses PHP & MySQL server technologies should be
saved in the ‘htdocs’ folder of your xampp folder. This will enable the xampp Server to
process the pages effectively.

Adding PHP to HTML document:


PHP is already perfectly at home with HTML—in fact, it is generally embedded within
HTML. Anything compatible with HTML on the client side is also compatible with PHP. By
now you’re probably wondering: How does the PHP parser recognize PHP code inside your
HTML document? The answer is that you tell the program when to spring into action by
using special PHP tags at the beginning and end of each PHP section. This process is called
escaping from HTML or escaping into PHP. Everything within these tags is understood by
the PHP parser to be PHP code. Everything outside of these tags does not concern the server
and will simply be passed along and left for the client to sort out whether it’s HTML or
JavaScript or something else. There are four major styles of PHP tags and different rationales
for using them. Part of the decision, however, is simply individual preference: what the
individual programmer is comfortable with or what a team has decided upon for reasons of
their own.

How to Create A PHP File

Any file containing PHP must have a ".php" file extension, like how HTML files, to be
identified as HTML files, must have a ".htm" or ".html" file extension.

4
PHP files can contain HTML in the same file, and still work properly. HTML files, on the
other hand, cannot contain a PHP script and still work properly, because the PHP code will be
read and displayed as HTML.

Also, while HTML files can be viewed in your browser from your own computer, PHP files
must run on a PHP-enabled web server and be viewed with your browser by going to the
file's URL (usually the website name + the file name + the file extension, for example:
http://www.yourwebsitename.com/test.php).

Text editors such as Notepad or WordPad on Windows machines, and Kwrite or Kate on
Linux machines, are a better option to save or create PHP files than Microsoft Word or Star
Office Writer. When saving the file, make sure that you type in the file name and the
extension (example: test.php) and that if there is a "Save as Type" dropdown option, that the
type is set to "All Files".

Better still, you can use code editors such as VS Code, Sublime Text, Atom etc.

Example

5
UNIT 2 – PHP SYNTAX

Opening/Closing PHP Tags

The PHP syntax is a set of rules that define how the program should be written. PHP is, in
that sense, no different from any other language. If I wrote this sentence backward and upside
down, it would not be following the rules, and it is doubtful that anyone would understand it.
The PHP interpreter expects certain rules to be followed and will spit errors at you if they are
not followed.

All code written in PHP must be identified as PHP code. A set of tags are used to mark the
beginning and end of a block of code, in between which any amount of code can be written.

(1) Canonical PHP tags: The most universally effective PHP tag style is: <?php ?> If you use
this style, you can be positive that your tags will always be correctly interpreted. Unless you
have a very, very strong reason to prefer one of the other styles, use this one. Some or all the
other styles of PHP tag may be phased out in the future—only this one is certain to be safe.

The standard opening tag is: <?php

The standard closing tag is: ?>

These tags can be used to jump in and out of "PHP mode" any number of times in a PHP file,
including a PHP file containing HTML elements.

<?php /*Code Can Go Here*/ ?>


Example
<html>
<head>
<?php /*Code Can Go Here*/?>
</head>
<body>
<?php /*Code Can Go Here*/?>
</body>
</html>
<?php /*Code Can Go Here*/?>

(2) HTML script tag: Although this is effective and gets around the FrontPage problems, it can
be cumbersome in certain situations, such as quick pop-in variable replacement. Be careful if
you use lots of JavaScript on your site since the close-script tags are fatally ambiguous. The
HTML script tag is best used for sizable blocks of PHP code.

<script language="php"> </script>

6
(3) Short-open tags: Short tags are, as one might expect, the shortest option. Those who
escape into and out of HTML frequently in each script will be attracted by the prospect of
fewer keystrokes; however, the price of shorter tags is pretty high. You must do one of two
things to enable PHP to recognize the tags:
 Choose the --enable-short-tags configuration option when you’re building PHP.
 Set the short_open_tag setting in your php.ini file to on. This option must be disabled
to parse XML with PHP because the same syntax is used for XML tags.
There are several reasons to resist the temptation of the short-open tag. The most compelling
reason now is that this syntax is not compatible with XML—and since XHTML is a type of
XML, this implies that none of your code will be able to validate as XHTML. PHP code
written with short-open tags is less portable because you can’t be sure another machine will
have enabled them. Short-open tags are also harder to pick out visually on the page, and
many syntax-highlighting schemes don’t support them. Beginners should be encouraged to
start off with the canonical style tag if at all possible.

<? PHP code goes here ?>

(4) ASP tags: <% PHP code goes here %>

Classwork: Hello world program


Now we’re ready to write our first PHP program.

A. Creating PHP page in Dreamweaver: A PHP page can be created in Dreamweaver


through the following steps:
1. Open a new file in Dreamweaver or VS code and type:
2. Click File> New
3. In the category section, click Dynamic page
4. Choose a local site folder where your website files will be stored
5. In the Dynamic page section click PHP and then click Create.
6. Type the following PHP code

<HTML>
<HEAD><TITLE>My first PHP program</TITLE>
</HEAD>
<BODY>
<?php
echo “Hello, world”;
?>
</BODY>
</HTML>
7. Save as “helloWorld.php” in your site folder.
8. Previewing in a Browser:
i. Click the Preview button or press F12.
ii. Select your preferred browser to view the webpage.

NOTE:
PHP page looks almost the same as a pure HTML page. The difference is that Dreamweaver
will add .php extension to the filename anytime you attempt to save the page. This will
enable the xampp Server to process the page as a PHP page.
7
B. Creating PHP page in VS Code: A PHP page can be created in VS Code through the
following steps:

1. Create a folder 'my_project' by going to your c-drive, open the xampp folder and then
open htdocs as follows: C:\xampp\htdocs\my_project
2. Launch your VS Code or some other text editor
3. Open the folder 'my_project' you created in (i)
4. Create a new file inside the folder 'my_project' and type the following PHP code:

<HTML>
<HEAD><TITLE>My first PHP program</TITLE>
</HEAD>
<BODY>
<?php
echo “Hello, world”;
?>
</BODY>
</HTML>

5. Save the php code as 'helloWorld.php' which should automatically be inside the
following directory: C:\xampp\htdocs\my_project\helloWorld.php
6. Running Your PHP Script:
i. Open a web browser.
ii. Type http://localhost/my_project/helloWorld.php in the address bar.
iii. You should see “Hello, World” displayed on the page.

NOTE:
At any given moment in a PHP script, you are either in PHP mode or you’re out of it in
HTML. There’s no middle ground. Anything within the PHP tags is PHP; everything outside
is plain HTML, as far as the server is concerned.

PHP Instruction Termination

Each statement made in PHP needs a method of indicating the end of the statement so that
each instruction can be carried out without mix-up. The semicolon ";" is used for this
purpose.

<?php
$variable=”My First PHP program”;
echo $variable;
?>

The block of code above contains two separate instructions inside the opening and closing
PHP tags. Each statement, or instruction, is terminated with a semicolon. Many errors are
caused by forgetting to terminate a statement.

8
The closing PHP tag can be used as instruction termination, making the following block of
code an option if code is not added between the second statement and the closing tag:

<?php
$variable=”Hello World”;
echo $variable
?>

PHP Comments

If the urge ever hits to write something down in the middle of a block of PHP code, you can
do this in one of two ways.

1. You can type in your comment and move on, causing errors in your program.
2. You can label your comment as a comment and move on without causing errors (assuming,
of course, that all the other code is correct).

Hopefully you will choose the second option, in which case you once again have two options.

1. You can comment out a single line of code – Single line comment style
2. You can comment out a large block of code – C- Style Multi line comment style.

Comments are most often used for two purposes:

1. Documentation: To note what is happening at certain points throughout a block of code.


(You will probably be thankful for properly used comments years later when you return to
your own long-untouched code, or try to understand another programmer's code!)

2. Testing:To temporarily keep a line or multiple lines of code from being interpreted,
without deleting it completely (a useful option during testing).

Comments are never seen by anyone who cannot see the php code. Three different methods
can be used to create comments:

// single line comment style

# single line comment style

/* */ multi line comment style

They can be used in the following manner:

<? Php
// This comment only spans one line
// It can, however, be used on as many lines as necessary.
# This comment only spans one line
# It is not used as commonly as the previous type
9
/* This comment can span one line*/
/* This comment can also span as many lines as needed.
It is useful when commenting out large chunks of code at a time.
This type of comment cannot be nested, or errors will occur*/
?>

PHP Whitespace

Whitespace is not significant to the PHP interpreter. You can make indentations and have
multiple blank rows anywhere in your code without creating problems.

The extra whitespace in the following examples is all ignored by the interpreter:

1. <?php echo “learning PHP is so much fun.”;?>


2. <?php
echo “Come on board!”;

?>
3. <?php

echo “At the end of this lesson, you’ll say I told you so.”;

?>

10
UNIT 3- PHP BASICS

PHP Output Statement

PHP gives two options to choose between to output text to the browser. Although the two
options are similar, "echo" is used far more than "print" because it is generally faster, shorter
to type, and sounds cool! For the examples in this tutorial, we will be using echo exclusively,
so let's learn all about it.

The ‘echo’ Statement

<?php

$numbers = 123;

echo "Why did the lizard go on a diet?";

echo 'It weighed too much for its scales!';

echo $numbers;

?>

Echo accepts both variables and strings (in single or double quotes). Variables can be
"echoed" by themselves, or from inside of a double-quoted string, but putting variable names
inside a single-quoted string will only output the variable name.

Example:

<?php

$numbers = 123;

echo "There are only 10 numbers. These numbers are: $numbers";

echo 'There are only 10 numbers. These numbers are: $numbers';

?>

The example above will result in:

There are only 10 numbers. These numbers are: 123

There are only 10 numbers. These numbers are: $numbers

11
You can also give multiple arguments to the unparenthesized version of echo, separated by
commas, as in:
echo “This will print in the “, “user’s browser window.”;

The parenthesized version, however, will not accept multiple arguments:


echo (“This will produce a “, “PARSE ERROR!”);

Print
The command print is very similar to echo, with two important differences:
- Unlike echo, print can accept only one argument with or without parentheses
- Unlike echo, print returns a value, which represents whether the print statement
succeeded.
The value returned by print will be 1 if the printing was successful and 0 if unsuccessful. (It
is rare that a syntactically correct print statement will fail, but in theory this return value
provides a means to test, for example, if the user’s browser has closed the connection.). Both
echo and print are usually used with string arguments, but PHP’s type flexibility means that
you can throw pretty much any type of argument at them without causing an error. For
example, the following two lines will print exactly the same thing:
print(“3.14159”); // print a string
print(3.14159); // print a number

HTML elements can be echoed as part of a string or variable, but they will be interpreted by
the browser instead of being displayed as part of the string or variable. This brings up an
interesting point, because when double quotes are used to begin and end a string, using
double quotes inside of the string will cause errors. The same applies to single quotes. The
following examples will cause errors:

<?php

echo "<p style="color: green;"></p>";

echo 'What's this? An error message?';

?>

There are two ways to fix this problem (besides the obvious "don't use quotes inside your
string"). One way is to use only double quotes inside of single quotes, and to use only single
quotes inside of double quotes. The better way is to "escape" each quote that would create a
problem.. The escape character is a backslash \. The following examples will not cause
errors:

<?php

echo '<p style="color: green;"></p>';

echo "<p style=\"color: green;\"></p>";

echo "What's this? No error message?";

12
echo 'What\'s this? No error message?';

?>

These rules, since they apply to strings, work the same with variables as they do with the
echo statement.

String Escape Characters

What happens when there are single quotes inside a single-quoted string, double quotes inside
a double-quoted string, or you actually want the dollar sign to be a part of your string instead
of referencing a variable? The backslash is used to escape characters such as these in double-
quoted strings. The only character inside a single-quoted string that will require escaping is a
single quote (apostrophe).

Character Meaning
\' Escapes A Single Quote In A Single-Quoted String
\" Escapes A Double Quote In A Double-Quoted String
\$ Escapes A Dollar Sign In A Double-Quoted String
\\ Escapes A Backslash In A Double-Quoted String
\n Creates A New Line, Not In HTML, But In Files, Etc.

Examples:

<?php

$string = 'This string\'s extra apostrophe is escaped.';

$string = "This \"string\" contains escaped double quotes.";

$string = "This \$0.00 string contains an escaped dollar sign.";

?>

PHP Variables

Variables are PHP's method of storing values, or information. Once a variable is set, it can be
used repeatedly, saving you the work of typing in the value again and again, and allowing
you to assign new values spontaneously.

In PHP, variables are identified by a dollar sign, immediately followed by a variable name.
Variable names are case-sensitive, but you can name your own variables if they abide by the
following basic rules:

1. Variable names cannot contain spaces.


2. Variables names can only contain letters (a-z and A-Z), numbers (0-9) and underscores (_).
3. Variable names can only begin with a letter or an underscore but cannot begin with
13
numbers.
4. Variable names should make sense so that you can remember them later!

Several examples of variables being assigned are below:

<?php

$NonSensical_ Variable_Name = “I am a variable value”;

$empty_variable = “ ”;

$eyes = “brown”;

$age = 35;

?>

As you can see, value is assigned to a variable using the "equal to" symbol, after which the
value is declared. Numerical values do not require single or double quotes, but strings do to
identify the beginning and end of each string.

Most programming languages make you declare the data type of each variable that you set,
but PHP automatically decides the data type of each variable for you, saving you the trouble
of declaring each one. Any value set using single or double quotes will be a string, including
numerical values. Numerical values set without using single or double quotes will be
integers, which can be used to perform mathematical calculations, etc. There are eight
different data types, including strings and integers.

Using Variables to Store User Input

You can also use variables to store information provided by users, such as form input. For
example, if you have a form where users can input the quantity they want to buy, you can
store that input in a variable.
<!-- HTML Form -->
<form method="post" action="process.php">
Quantity: <input type="number" name="quantity">
<input type="submit" value="Calculate">
</form>

<!-- PHP Script (process.php) -->


<?php
$bicyclePrice = 80; // Discounted price
$quantity = $_POST['quantity']; // Get the quantity from the form input
$totalRevenue = $bicyclePrice * $quantity;

14
echo "Selling " . $quantity . " bicycles at " . $bicyclePrice . " each will generate " .
$totalRevenue . " in total revenue.";
?>
In this example, the quantity is taken from user input and used to calculate the total revenue
dynamically.
Dynamic PHP Variables

Usually, a variable is created with a dollar sign followed by the variable name. But the
variable name itself can be stored in a variable.

Example

<?php
$var1 = "Hello";

// is equivalent to

$var2 = "var1";
$$var2 = "Hello";
?>

The $var2 variable contains the string "var1", hence $$var2 has a dollar sign followed by the
value of $var2 which is interpreted as "Hello". When accessing a dynamic variable, the
syntax is the same.

Example

<?php
$var1 = "Hello";
echo $var1;

// is equivalent to

$var2 = "var1";
$$var2 = "Hello";
echo $$var2;
?>

However, if you want to put a dynamic variable within a string, it needs to be enclosed in
braces.
Example

<?php
$var1 = "Hello" ;
$var2 = "var1";

15
echo "$$var2";
?>

The code does not print "Hello" but instead prints $var1. This is because whenever a variable
is placed within " ", PHP helpfully inserts its value. This it should be written those way
instead:

<?php
$var1 = "Hello" ;

//is equivalent to

$var2 = "var1";
echo "${$var2 }; // prints "Hello"
?>
Passing PHP variables by reference

Variables are assigned by values. Thus, if we are to assign $var to $newVar, a copy of the
value held in $var will be stored in $newVar. Consequently, changing the value of $var
would have no effect on the contents of $newVar. To change this behaviour, there is a need
to force a reference to $var that is assigned to $newVar. This can be achieved by adding (&)
in front of the $var to ensure a reference to this variable rather than a copy of its content.

Example

<?php
$var = 10;
$newVar = &$var;
$var = 100;
echo $newVar;
?>

PHP Data Types

Let’s look at the different types of data that can be stored in variables. Although PHP
automatically assigns the data type of each variable based on the data that it contains, it will
be good to know a little about each one.

Type Type Description


String Scalar Sequences of Characters in single or double quotes
Whole Number, Positive or Negative, Without a
Integer Scalar
Decimal Point
Float (Also Floating-Point
Scalar Floating Numbers, With a Decimal Point
or Double)
Has Only Two Possible Values: "TRUE" or
Boolean Scalar
"FALSE"
Array Compound Named/Indexed Collection of Other Values

16
Object Compound Programmer-Defined Classes
Hold References to External Resources (Database
Resource Special
Connections, Etc.)
NULL Special Has Only One Possible Value: NULL

Constants:
In addition to variables, which may be reassigned, PHP offers constants, which have a single
value throughout their lifetime. Constants do not have a $ before their names, and by
convention the names of constants usually are in uppercase letters. Constants can contain
only scalar values (numbers and string). Constants have global scope, so they are accessible
everywhere in your scripts after they have been defined—even inside functions. The syntax
for defining constant is:
define (name, value, case insensitivity=false)
It takes three parameters: the first parameter defines the name of the constant; the second
parameter defines the value of the constant and the optional third parameter specifies whether
the constant name should be case- insensitive. Default value for the third parameter is false.
This means that whenever the third parameter is omitted, the constant will be case sensitive.

The example below creates a case-sensitive constant, with the value “Welcome to PHP
class”.

Example
<?php
define (“GREETING”, “Welcome to PHP class”);
echo GREETING;
?>

The example below creates a case- insensitive constant with the value “Welcome to PHP
class”.

Example
<?php
define (“GREETING”, “Welcome to PHP class”, true);
echo greeting;
?>

PHP Operators

Operators perform operations. They are symbols, or combinations of symbols, that assign
value, combine values, or compare values, to name just a few of their uses. Without
operators, PHP is pretty much useless. In fact, you have already been introduced to several
operators without even realizing it!

PHP operators can be broken down into several categories, which we will now review,
beginning with the operators that we have already learned.

Assignment Operators
17
Very simply, assignment operators assign value. We have already used the assignment
operator to assign values to variables.

Operator Description
= Assigns A Value

Example: <?php

$variable = "abcde";

echo $variable; // Result: abcde

?>:

String Operators

String Concatenation (The "Dot" Operator)

The word "concatenate" means "to link together, or to unite in a series or a chain". It is
possible to link together a series of one or more strings using the concatenation or "dot"
operator, as it is informally called. Let's look at an example first.

<?php

$variable1 = "abcdefghijklm";

$variable2 = "nopqrstuvwxyz";

$variable3 = $variable1 . $variable2;

echo $variable3;

echo $variable1 . $variable2;

?>

What we see in our example are two variables containing strings, and a third variable using
the concatenation operator to combine those two variables and store the contents of them both
in a new variable. When the contents of the third variable are sent to the browser, the result
will be "abcdefghijklmnopqrstuvwxyz", because the concatenation operator added what
was on the right (variable #2) to the end of what was on the left (variable #1).

18
String concatenation can be performed directly from within an echo statement as well. And,
in both variables and in the echo statement, strings and variables can be interchangeably
concatenated.

<?php

$variable1 = "abcdefghijklm";

$variable2 = "nopqrstuvwxyz";

echo "The letters of the alphabet are: " . $variable1 . $variable2;

?>

Can you see what the result will be?

The letters of the alphabet are: abcdefghijklmnopqrstuvwxyz

String Concatenation Assignment

The assignment operator .= is used as a shortcut to concatenate two strings without


assigning a new variable. It takes an existing variable and adds a new string onto the end
(right side) of that variable's existing string.

<?php

$variable = "01234";

$variable .= "56789";

echo $variable;

?>

The result is:

0123456789

String operators, as we have learned, can either link two strings together, or add one string to
the end of another string.

Operator Description
. Concatenates (Links) Two Strings Together
.= Adds A String Onto the End of An Existing String

19
<?php

$variable = "abcde" . "fghij";

$variable .= "klmno";

echo $variable; // Result: abcdefghijklmno

?>

Arithmetic Operators

Math! Some people like it and some people don't. Why not have fun writing a PHP script that
does your math for you?

Operator Description
+ Addition Operator (Adds Two Values Together)
- Subtraction Operator (Subtracts One Value From Another)
* Multiplication Operator (Multiplies Two Values)
/ Division Operator (Divides One Values From Another)
% Modulus Operator (Determines The Remainder of a Division)

Arithmetic operations can be performed on variables, within variables, echoed directly, etc.

<?php

$addition = 5 + 5;

echo $addition; // Result: 10

$subtraction = 5 - 5;

echo $subtraction; // Result: 0

$multiplication = 5 * 5;

echo $multiplication; // Result: 25

$division = 5 / 5;

20
echo $division; // Result: 1

$modulus = 7 % 5;

echo $modulus; // Result: 2

echo 3 + 5 / 2; // Result: 5.5

?>

What?! It made sense until the last example, right? If you were expecting the results of the
last example to be "4", then you might not have known about operator precedence, which
states that multiplication and division come before addition and subtraction. To solve this
problem you can use parenthesis to group the numbers that you want to be calculated first.

This rule is also known as PEMDAS (Parentheses, Exponents, Multiplication, Division,


Addition, Subtraction), BEDMAS (Brackets, Exponents, Division, Multiplication, Addition,
Subtraction), BIDMAS (Brackets, Indices, Division, Multiplication, Addition, Subtraction) or
BODMAS (Brackets, Orders, Division, Multiplication, Addition, Subtraction).

<?php

echo (3 + 5) / 2; // Result: 4

?>

Problem solved; happy calculating!

Combined Assignment Operators

Combined assignment operators are shortcuts useful when performing arithmetic operations
on an existing variable's numerical value. They are similar to the concatenation assignment
operator.

Operator Description
+= Adds Value to An Existing Variable Value
-= Subtracts Value From Existing Variable Value
*= Multiplies An Existing Variable Value
/= Divides An Existing Variable Value
%= Modulo of An Existing Variable Value And New Value

Example before combined assignment operator is used:

21
<?php

$variable = 8;

$variable = $variable + 3;

echo $variable; // Result: 11

?>

Example of combined assignment operator in use:

<?php

$variable = 8;

$variable += 3;

echo $variable; // Result: 11

?>

Incrementing/Decrementing Operators

There are shortcuts for adding (incrementing) and subtracting (decrementing) a numerical
value by one.

Operator Description
++ Incrementation Operator (Increases A Value By 1)
-- Decrementation Operator (Decreases A Value By 1)

<?php

$variable = 15;

$variable++;

echo $variable; // Result: 16

$variable--;

echo $variable; // Result: 15

?>

22
Comparison Operators

Comparison operators compare two values and return either true or false, depending on the
results of the comparison. They are used in conditions, which we will study in the next
chapter.

Operator Description Example


== Is Equal To 3= =2 (Will Return "False")
=== Identitical Returns true if both values and datatype are true
!= Is Not Equal To 3!=2 (Will Return "True")
<> Is Not Equal To 3<>2 (Will Return "True")
Returns true if either the values or datatypes are
!= = Not identical
different.
> Is Greater Than 3>2 (Will Return "True")
< Is Less Than 3<2 (Will Return "False")
>= Is Greater Than or Equal To 3>=2 (Will Return "True")
<= Is Less Than or Equal To 3<=2 (Will Return "False")

Logical Operators

Logical operators usually work with comparison operators to determine if more than one
condition is true or false at the same time.

Operator Meaning Description


&&/ and And True If Two Statements Are True, Otherwise False
||/ or Or True If One Statement or Another Is True, Otherwise False
! Not True If Statement Is False, False If Statement Is True

Logical operators make more sense when they are applied to practical examples.

Ternary Operator
One especially useful construct is the ternary conditional operator, which plays a role
somewhere between a Boolean operator and a true branching construct. Its job is to take three
expressions and use the truth value of the first expression to decide which of the other two
expressions to evaluate and return. The syntax looks like:

test-expression ? yes-expression : no-expression

The value of this expression is the result of yes-expression if test-expression is true;


otherwise, it is the same as no-expression. For example, the following expression assigns to
$max_num either $first_num or $second_num, whichever is larger:

$max_num = $first_num > $second_num ? $first_num : $second_num;

23
UNIT 4 – PHP CONDITIONS AND LOOPS

Control Structure
This kind of program reaction requires a control structure, which indicates how different
situations should lead to the execution of different code. The two broad types of control
structures we will talk about are branches and loops. A branch is a fork in the road for a
program’s execution—depending on some test or other, the program goes either left or right,
24
possibly following a different path for the rest of the program’s execution. A loop is a special
kind of branch where one of the execution paths jumps back to the beginning of the branch,
repeating the test and possibly the body of the loop.

1. Branching
The two main structures for branching are if and switch. If is a workhorse and is usually the
first conditional structure anyone learns. Switch is a useful alternative for certain situations
where you want multiple possible branches based on a single value and where a series of if
statements would be cumbersome.

if

Growing up, we are all familiar with the statement "you can have your sweets if you finish
your meal first". It was an early introduction to the wonderful world of conditions, which are
very common in our everyday lives. Whether we think about it or not, most decisions we
make are based on at least one condition being met--or not met. Conditions are very
important in programming.

The "if statement" is the most common conditional statement used in php. It will perform an
action (such as having sweets) if the specified condition is met, or true (such as finishing the
meal). If the condition is not met, or false, the action will not be performed.

The if statement syntax places the condition in parenthesis, followed by the result in curly
brackets, in the following manner:

if (condition)

action to take

Example

<?php

$number = 5;

if ($number>3) { echo "Condition is met!"; }

?>

Remember in the last unit how we studied php comparison operators? The "is greater than"
comparison operator ">" is used in this example to compare two values. Our example, when
translated to English, says: if the value of the number variable is greater than 3, echo that the
condition is met. Since this condition is true, the action will be performed.

Conditions are not at all limited to comparing numerical values.

25
<?php

$tell_joke = "yes";

if ($tell_joke= ="yes") {

echo "How do you spot a modern spider?<br>";

echo "She doesn't have a web she has a website!<br>";

?>

else

The if statement can be taken a step further with the else statement, used specifically as a
follow-up to the if statement. What happens when an if statement is false? The else statement
allows you to handle this possibility.

The else statement syntax is similar to the if statement syntax, but lacks a condition, and
cannot be used alone. It must directly follow an if statement.

if (condition is true)

action to take

else

alternative action to take

Example 1

<?php

$question = "What is the biggest ant in the world?";

26
$answer = "An elephant!";

if ($answer=="An elephant!") { echo "Yep, congrats."; }

else { echo "Nope, sorry."; }

?>

In this example the condition is true (the answer is "An elephant!") so the else statement is
ignored. If the condition was false, the else statement would be used:

Example 2

<?php

$age = 15;

$discount_age = 60;

if ($age>=$discount_age) {

echo "Congratulations! You qualify for our senior discount.";

} else {

echo "Sorry, but you do not qualify for our senior discount.";

?>

Now we see a condition stating that if the age is greater than or equal to the discount age,
you would qualify for a senior discount, otherwise (else) you will not qualify. Unless you
significantly raise the value of the age variable, there will be no senior discounts for you!

Next up we will learn how to add additional conditions into an if...else statement using elseif.

elseif

If you like cheese you must be a mouse, else if you like lettuce you must be a rabbit, elseif
you like chocolate you must be a human, else you must be a turtle. Yeah, that doesn't make
much sense, but it's a fun way to get into the conditional programming mentality!

27
The elseif statement follows the if statement as a method of specifying (checking) alternative
conditions to the if statement. Multiple elseif statements can be used.

if (condition)

action to take

elseif (condition)

another action

elseif (condition)

yet another action

else

final action

Example

<?php

$color = "orange";

if ($color=="purple") {

echo "Purple conveys royalty, nobility & wisdom.";

} elseif ($color=="orange") {

echo "Orange conveys energy, warmth & flamboyancy.";

} elseif ($color=="blue") {

28
echo "Blue conveys peace, tranquility & security.";

} else {

echo "I dunno what that color conveys, sorry.";

?>

After examining the example, can you determine which block of code will be executed when
this program is run? If you guessed "the orange one" then we have a winner!

When a true condition is reached, php will skip the remaining elseif and else statements in
that block, meaning that since the orange condition was true, the blue condition is never
checked and the else statement is ignored. The else statement is not required at the end, but
should be used if there is any possibility of the condition(s) not being met.

Switch

Sometimes, multiple if/elseif/elseif statements are just not the most efficient option when
checking for a specific condition. The switch statement can replace multiple if/elseif/elseif
statements when you want to determine whether or not one value is equal to one of many
other values in a more efficient manner.

The switch statement begins by accepting a single value, which it compares against multiple
cases. When the case, or condition, is met (true), the specified block of code is executed, and
the remainder of the switch statement is skipped.

The syntax is as given below:

switch(expression)
{
case value-1:
statement-1
statement-2
...
[break;]
case value-2:
statement-3
statement-4
...
[break;]
...
[default:
default-statement]
}

Example

29
<?php

$time = "3 A.M.";

switch ($time) {

case "3 P.M.":

echo "Good afternoon!";

break;

case "9 P.M.":

echo "Good evening!";

break;

case "3 A.M.":

echo "Good night!";

break;

case "9 A.M.":

echo "Good morning!";

break;

default:

echo "Hello!";

break;

?>

In our example, we begin by providing the switch statement with a value in the form of a
variable. That value is compared against multiple cases, each of which contain their own
value and end with a full colon rather than the standard semi-colon.

The switch statement accepts multiple lines of code in each block of code following each
case, however our example only has a single line of code that should be run in the event that
the case (condition) is true. Each block ends with a break to indicate that the remainder of the
30
switch statement should be skipped after the case is true and the associated block of code is
run.

The "default:" portion of the switch statement is similar to the else clause used with if
statements. It determines what is to be done if none of the cases are true.

So do you know what the result of our switch statement is yet?

Good night!

Looping

This is the construct used for iteration. They are; while, do –while, for and foreach
statement.

while
Repetition is something that we all experience. Every night we go to bed, and every morning
we get up. It is an endless cycle that loops back to begin all over again. When programming,
it is very common to need to repeat the same task over and over again. You can either do this
by hand (spending unnecessary time pounding on your keyboard) or you can use a loop.

while(condition)

action to take

PHP "while" loops will run a block of code over and over again as long as a condition is true.
PHP "for" loops will run a block of code a specified number of times, which we will learn
more about later.

The while loop evaluates the condition expression as a Boolean—if it is true, it executes
statement and then starts again by evaluating condition. If the condition is false, the while
loop terminates. Of course, just as with if, statement may be a single statement or it may be a
brace-enclosed block. The body of a while loop may not execute even once since it is a
pretest construct.

Example

<?php

$count = 1;

while ($count<=100) {

echo $count . "<br>";

$count++;

31
}

?>

What does this code do? It echoes the numbers 1-100 with only one number per line. How do
five lines of code produce 100 lines? Loops!

After setting a variable with a value of 1, our example sets up a loop that states "while the
count is less than or equal to 100, run the following block of code". The block of code
echoes the current value of the variable, then increases that value by 1. The loop performed
this action until the value of $count was equal to 101, at which point in time the condition
was no longer true and the loop was terminated.

A common mistake when running a loop like this is to forget to increment the value of the
variable. This causes an endless loop running the exact same code over and over again.

do-while

The do-while loop is very similar to the while loop, with one major difference. The
condition is checked after running each loop instead of before. The "do" part comes
before the "while" part, so the block of code is run once even if the condition is false.

do

action to take

while (condition)

Example

<?php

$count = 1;

do {

echo $count . "<br>";

$count++;

32
while ($count<=5);

?>

This example results in the numbers 1-5 being echoed on separate lines.

The do-while loop is not used often.

for

For loops can be used when you know in advance how many times a block of code should be
run. They are more complex than while loops, but understandable once they are broken down
and explained. They are more compact than while loops, making them popular for many uses.

Their syntax is:

for (initialize; condition; increment)

action to take

Instead of accepting only a single condition, like a while loop does, the for loop accepts three
different expressions separated by semi-colons.

The first expression (initialize) sets, or initializes, a variable with a numerical value that can
be used as a counter. When learning about "while" loops, we set this variable before the loop
began, but "for" loops include this variable when beginning the loop. This expression is only
run at the beginning of the loop, after which it is ignored.

The second expression is the condition, which behaves no different than the conditions that
we have already discussed. It is checked at the beginning of every loop.

The third expression is the increment, which, in a while loop, is included as part of the
action to be taken, but in a for loop is one of the expressions initially set. It is run each time
the loop is run.

Let's see a for loop in action.

Example

33
<?php

$number = 75;

for ($count=1; $count<=10; $count++) {

echo $number . "<br>";

$number += 75;

?>

What our example is doing is using the $count variable as a counter to determine how many
times the loop is run. It is set, evaluated, and incremented all in one statement. The block of
code that follows simply echoes the current value of the $number variable, then adds 75 to
that value. The loop is run 10 times, as specified in the condition.

The result will look like this:

75

150

225

300

375

450

525

600

675

750

For loops are fun to experiment with, and exhilarating when they actually do what you want
them to for the first time ever!

34
Break and Continue
The standard way to get out of a looping structure is for the main test condition to become
false. The special commands break and continue offer an optional side exit from all the
looping constructs, including while, do-while, and for:
- The break command exits the innermost loop construct that contains it.
- The continue command skips to the end of the current iteration of the innermost loop
that contains it.

Breaking Out of Loops

There will be time when you want to break out of, or end a loop before it is complete, usually
when a certain condition is met. The break statement makes this possible.

<?php

$number = 75;

for ($count=1; $count<=10; $count++) {

if ($number>300) { break; }

echo $number . "<br>";

$number += 75;

?>

By adding a single line of code to the for loop that we have already examined, we can see the
break statement in action. If the value of the number variable is greater than 300, the break
statement is executed. When the break statement is executed, the loop is abruptly broken out
of, so that the remaining code and remaining/unfinished loops are all ignored.

The result will be:

75

150

225

300

35
If multiple loops are nested, the break statement accepts a numerical value to indicate how
many loops to break out of. The statement "break 1;" is the same as saying "break;", so to
break out of two loop at once the correct statement is "break 2;" etc.

<?php

$a = 0;

$b = 7;

while ($a<50) {

for ($c=0; $c<3; $c++) {

$b = $b + $b - 2;

echo $b . "<br>";

if ($b>500) { break 2; }

$a++;

?>

So in this example we see a while loop that contains a for loop that contains a condition
saying "if the $b variable value is greater than 500, break out of 2 loops". Can you figure out
what else this block of code is saying, and what the result will be?

I'll give you a hint:

12

22

42

82

162

36
322

642

For example, the following code:


for ($x = 1; $x < 10; $x++)
{
// if $x is odd, break out
if ($x % 2 != 0)
break;
print(“$x “);
}

Prints nothing, because 1 is odd, which terminates the for loop immediately. On the other
hand, the code:
for ($x = 1; $x < 10; $x++)
{
// if $x is odd, skip this loop
if ($x % 2 != 0)
continue;
print(“$x “);
}

Prints:
2468

The reason is because the effect of the continue statement is to skip the printing of any odd
numbers.

37

You might also like