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

Building Web Applications in PHP

The document provides an overview of building web applications in PHP, covering essential topics such as the interaction between web browsers and servers, the request/response cycle, and basic PHP syntax including variables, data types, and error handling. It emphasizes the importance of understanding concepts rather than memorizing features, particularly for beginners. Additionally, it introduces superglobal variables and their role in creating secure applications.

Uploaded by

losthit69
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Building Web Applications in PHP

The document provides an overview of building web applications in PHP, covering essential topics such as the interaction between web browsers and servers, the request/response cycle, and basic PHP syntax including variables, data types, and error handling. It emphasizes the importance of understanding concepts rather than memorizing features, particularly for beginners. Additionally, it introduces superglobal variables and their role in creating secure applications.

Uploaded by

losthit69
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 41

7/1/2021 Building Web Applications in PHP - ITEXAMTOOLS

    

Visit the Shop for Amazing and very useful software and tools! Dismiss 
books & Digital learning International Degrees Learning New Posts Free IT Dumps

Free Software E-Hacking Tools Shop Cart Checkout My account 
How to setup Jupyter Notebook In python How to create Arrays in python using NumPy 

ITEXAMTOOLS
Cisco Press Publications | Online
Degrees | Pearson e-Books | Q&A and
FREE downloads IT Learning Lessons

Home CISCO ALL Cisco Career Certifications VMware About

Contact Us

DISCLOSURE

ITExamtools.com Is
learner supported &

Building Web Applications in contains affiliate links,


meaning when you make

PHP a purchase, we receive a


small commission.
 success  Featured, PHP Edit Post

TOP online Courses

 Top 25 online courses in


Mexico
 Top 25 online courses in
Thailand
 Top 25 online courses in
New Zealand
 Top 25 online courses in
Pakistan
Easy IN-Page Links 
 Top 25 online courses in
Nigeria
Building Web Applications in PHP covers the following
 Top 23 online courses in
asapects to learn: Canada

https://itexamtools.com/building-web-applications-in-php/ 1/41
7/1/2021 Building Web Applications in PHP - ITEXAMTOOLS

How a web browser interacts with a web server, Top 25 online courses in

India
request/response cycle, including GET/POST/Redirect.
an introductory understanding of Hypertext Markup  Top 25 online courses in
Oman
Language (HTML), as well as the basic syntax and data
 Top 25 online courses in
structures of the PHP language, variables, logic, iteration, Qatar
arrays, error handling, and superglobal variables, among
 Top 25 online courses in
other elements. An introduction to Cascading Style South Africa
Sheets (CSS) will allow you to style markup for web  Top 25 online courses in
pages, & the skills and knowledge to install and use an Malaysia
integrated PHP/MySQL environment like XAMPP or  Top 25 online courses in
MAMP. Australia

First let us see the The Building search out the


best courses
Blocks of PHP
Data Science
This starting class covers some of the nuts and bolts of 2021 : Complete
Data Science &
the PHP scripting language, including a few PHP-specific
Machine
features with regards to global variables, data types, and Learning (
Udemy )
changing types.

Those of you new to programming might feel


The Data
BESTSELLER ON UDEMY*
overwhelmed at times, but don’t worry—you can always Science Course
refer to this chapter later on. Concentrate on 2021: Complete
Data Science
understanding the concepts, rather than memorizing the Bootcamp (
Udemy )
features covered, because these elements will be
repeated throughout the scripts in this book. Eventually
you’ll get it, if not the first time! Learn Business
Data Analysis
If you’re already an experienced programmer, you should with SQL and
Tableau ( Udemy
at least skim this chapter because it covers a few PHP- )
specific features with regards to global variables, data
types, and changing types.

In this chapter, you will learn


data-science-data-
driven-decision-
making

https://itexamtools.com/building-web-applications-in-php/ 2/41
7/1/2021 Building Web Applications in PHP - ITEXAMTOOLS
Media error: Format(s) not
About variables—what they are, why you need to use supported or source(s) not
found
them, and how to use them Download File:
data:image/gif;base64,R0lG
How to define and access variables ODdhAQABAPAAAP///wAA
ACwAAAAAAQABAEACAk
QBADs=
About data types Download File:
data:image/gif;base64,R0lG
ODdhAQABAPAAAP///wAA
About some of the more commonly used operators ACwAAAAAAQABAEACAk
QBADs=
How to use operators to create expressions

How to define and use constants

Master Data
Variables Science Career
Skills
A variable is a special container that you can define,
which will then “hold” a value, such as a number, string,
object, array, or a Boolean. Variables are fundamental to
programming. Without variables, you would be forced to
hard-code each specific value used in your scripts. The
following hard-coded statement adds two numbers
Top paying Jobs
together and prints the result, which solves a simple All over the World
mathematics problem:
 The best paying jobs in
echo (2 + 4); New Zealand
 The best paying jobs in
However, this snippet of code is useful only for people Thailand
who specifically want to know the sum of 2 and 4. To get
 The best paying jobs in
past this limitation, you could write a script for finding the Nigeria
sum of another set of numbers, say 3 and 5. However,  The best paying jobs in
this approach to programming is clearly absurd, and this Vietnam

is where variables come into play.  The best paying jobs in


Bangladesh
Variables allow you to create templates for operations,  The best paying jobs in
such as adding two numbers, without worrying about the Hong Kong

specific values the variables represent. Values will be  The best paying jobs in
South Africa
given to the variables when the script is run, possibly
through user input, through a database query, or from the  The best paying jobs in
the Philippines
result of another action earlier in the script. In other
 The best paying jobs in
words, variables should be used whenever the data in
Singapore

https://itexamtools.com/building-web-applications-in-php/ 3/41
7/1/2021 Building Web Applications in PHP - ITEXAMTOOLS

your script is liable to change—either during the lifetime  The best-paying jobs in
Canada
of the script, or when it is passed to another script for
later use.  The best-paying jobs in
Pakistan

A variable consists of a name of your choosing, preceded


by a dollar sign ($). Variable names can include letters, Mastering Data
Analysis
numbers, and the underscore character (_), but they
cannot include spaces. Names must begin with a letter or
an underscore. The following list shows some legal
variables:

$a;

$a_longish_variable_name;

$2453;

$sleepyZZZZ;
Free Learning
By the Way Resources

Try out a Learning Lab


Your variable names should be meaningful as well as
with free lessons
consistent in style. For example, if your script deals with
name and password values, don’t create a variable Teach Yourself jQuery and
JavaScript
called $n for the name and $p for the password—those
are not meaningful names for anyone other than you, at Teach Yourself JavaScript
that particular moment. If you pick up that script weeks Teach Yourself HTML and
later, you might think that $n is the variable for “number” CSS
rather than “name” and that $p stands for “page” rather
Teach Yourself HTML5
than “password.” And what if a co-worker has to modify Mobile App Development
your script? How will that person know
The Microsoft Press by
what $n and $p stood for? You can use whatever naming Pearson Free Sample
convention you want for variables in your scripts, as long chapters
as the names are descriptive and follow some sort of
Special Offer: Save 40%
pattern that others can understand. On Microsoft
Certification Titles
A semicolon (;)—also known as the instruction terminator
Microsoft Official Exam
—is used to end a PHP statement. The semicolons in the
Reference Books

https://itexamtools.com/building-web-applications-in-php/ 4/41
7/1/2021 Building Web Applications in PHP - ITEXAMTOOLS

previous fragment of code are not part of the variable Free chapters from Sams
Publishing
names, but are used to end the statement that declares
the variable as “alive and kicking,” if you will. To declare a SQL Queries:
variable, you need only include it in your script. When you Summarizing Data Results
from a Query in SQL
declare a variable, you usually assign a value to it in the
same statement, as shown here: Understanding How Java
Programs Work
$num1 = 8;
Understanding Dynamic
$num2 = 23; Websites and HTML5
Applications
The preceding lines declare two variables and use the
assignment operator (=) to assign values to them. You
will learn about assignment in more detail in the
“Operators and Expressions” section later in this chapter. Deal of the DAY –
Official IT Books
After you assign values to your variables, you can treat
them exactly as if they were the values themselves. In
other words

echo $num1;
Popular Recent
is equivalent to Comments Tags

echo 8;
Udemy Budget
Affordable
as long as $num1 is assigned a value of 8.
Discount sale
2021
Globals and Superglobals
Master of Applied
In addition to the rules for naming variables, there are
Data Science
rules regarding the availability of variables. In general, the
assigned value of a variable is present only within the
function or script where it resides. For example, if you Modeling
have scriptA.php that holds a variable called $name with Techniques in
a value of joe, and you want to create scriptB.php that Predictive
Analytics:
also uses a $name variable, you can assign to that
Analytics and Data
second $name variable a value of jane without affecting Science
the variable in scriptA.php. The value of

https://itexamtools.com/building-web-applications-in-php/ 5/41
7/1/2021 Building Web Applications in PHP - ITEXAMTOOLS

the $name variable is local to each script, and the IP Routing in the
LAN
assigned values are independent of each other.

However, you can also define the $name variable


as global within a script or function. If the $name variable Azure Sentinel –
is defined as a global variable in An Introduction

both scriptA.php and scriptB.php, and these scripts are


connected to each other (that is, one script calls the other
Python and Your
or includes the other), there will only be one value for the
Phone: Let’s Talk
now-shared $name variable. Examples of global variable About Kivy
scope will be explained in more detail in Chapter 7,
“Working with Functions.”
VCAP5-DCA
configure using
In addition to global variables of your own creation, PHP vSphere
has several predefined variables called superglobals.
These variables are always present, and their values are
10 Steps to
available to all your scripts. Each of the following Adopting Artificial
superglobals is actually an array of other variables: Intelligence in
Business
$_GET contains any variables provided to a script through
the GET method.
Learn Anything |
$_POST contains any variables provided to a script Learn step-by-step
anything you want
through the POST method.

$_COOKIE contains any variables provided to a script


through a cookie.

$_FILES contains any variables provided to a script


through file uploads.

$_SERVER contains information such as headers, file


paths, and script locations.

$_ENV contains any variables provided to a script as part


New Arrivals &
of the server environment. Sale offers

$_REQUEST contains any variables provided to a script


via GET, POST, or COOKIE input mechanisms.

$_SESSION contains any variables that are currently


registered in a session.
CCNA CCNP CCNP
200- and and
https://itexamtools.com/building-web-applications-in-php/ 6/41
7/1/2021 Building Web Applications in PHP - ITEXAMTOOLS
301 CCIE CCIE
The examples in this book will use superglobals wherever Enterpri data
se Core center
possible. Using superglobals within your scripts is core
important in creating secure applications because
superglobals reduce the likelihood of user-injected input
to your scripts. By coding your scripts to accept only what
AZ-104 Windo Introdu
you want, in the manner defined by you (from a form video ws cing
course Server Machin
using the POST method, or from a session, for example), 2019 e
Inside Learnin
you can eliminate some of the problems created by Out g
loosely written scripts.

New Arrivals &


Data Types Sale offers

Different types of data take up different amounts of


memory and may be treated differently when they are
manipulated in a script. Some programming languages
therefore demand that the programmer declare in Ruby DevOp
on s for
advance which type of data a variable will contain. By Rails VMwar
Tutorial e
contrast, PHP is loosely typed, meaning that it will , 6th Admini
Edition strators
determine the data type at the time data is assigned to
each variable.

This automatic typing is a mixed blessing. On the one


hand, it means that variables can be used flexibly—in one
instance, a variable can hold a string and then later in the
script it can hold an integer or some other data type. On
the other hand, this flexibility can lead to problems in
larger scripts if you are specifically expecting a variable to
hold one data type when in fact it holds something
completely different. For example, suppose that you have
created code to manipulate an array variable. If the
variable in question instead contains a number value and
no array structure is in place, errors will occur when the
code attempts to perform array-specific operations on the
variable.

https://itexamtools.com/building-web-applications-in-php/ 7/41
7/1/2021 Building Web Applications in PHP - ITEXAMTOOLS

Table 5.1 shows the eight standard data types available


in PHP.

Table 5.1. Standard Data Types

Type Example Description

Boolean true One of the special Site Navigation


values true or false

Integer 5 A whole number  Home


 CISCO ALL
Float or 3.234 A floating-point number
double  CCENT & CCNA
R&S
String “hello” A collection of characters
 CCNAv7
Object An instance of a class
 CCNA Data Center
Array An ordered set of keys and  CCNP Data Center
values
 Cisco Certified
Resource Reference to a third-party CyberOps
resource (a database, for Associate.
CBROPS 200-201
example)
 CCNA 200-301
NULL An uninitialized variable
(New CCNA)

Resource types are often returned by functions that deal  Cisco Career
with external applications or files. For example, you will Certifications
see references to “the MySQL resource ID” in Chapter  Cisco Collaboration
Exams
18, “Interacting with MySQL Using PHP.” The NULL type
 CCNP/CCIE
is reserved for variables that have been declared, but no
350-
value has been assigned to them. 801[CLCOR]
Q&A and More
PHP has several functions available to test the validity of
 CCNP/Speciali
a particular type of variable—one for each type, in fact. st 300-810
The is_* family of functions, such as is_bool(), tests [CLICA] Q&A
and more
whether a given value is a Boolean. Listing 5.1 assigns
different data types to a single variable and then tests the  300-815
[CLACCM]
variable with the appropriate is_* function. The comments
Q&A and more
in the code show you where the script is in the process.
 CCNP 300-820
[CLCEI] Q&A
By the Way
and more
https://itexamtools.com/building-web-applications-in-php/ 8/41
7/1/2021 Building Web Applications in PHP - ITEXAMTOOLS

You can read more about calling functions in Chapter 7.  CCNP 300-835
[CLAUTO] Q&A
Listing 5.1. Testing the Type of a Variable and more

1: <?php
 Cisco CyberOps
2: $testing; // declare without assigning
3: echo "is null? ".is_null($testing); // checks if n
Exams
4: echo "<br/>";  CyberOps
5: $testing = 5; Associate 200-
6: echo "is an integer? ".is_int($testing); // checks 201 CBROPS
7: echo "<br/>";
Q&A and more
8: $testing = "five";
9: echo "is a string? ".is_string($testing); // check  CyberOps
10: echo "<br/>"; Professional
11: $testing = 5.024; 350-201
12: echo "is a double? ".is_double($testing); // check
[CBRCOR]
13: echo "<br/>";
14: $testing = true;
Q&A and more
15: echo "is boolean? ".is_bool($testing); // checks i  CyberOps
16: echo "<br/>"; Professional
17: $testing = array('apple', 'orange', 'pear');
300-215
18: echo "is an array? ".is_array($testing); // checks
19: echo "<br/>";
[CBRFIR] Q&A
20: echo "is numeric? ".is_numeric($testing); // check and more
21: echo "<br/>";
22: echo "is a resource? ".is_resource($testing); // c  Cisco Data Center
23: echo "<br/>"; Exams
24: echo "is an array? ".is_array($testing); // checks
 CCNP Data
25: echo "<br/>";
26: ?>
Center 350-601
[DCCOR] Cisco
Certified
Specialist
Put these lines into a text file called testtype.php, and
place this file in your web server document root. When  CCNP Data
Center 300-610
you access this script through your web browser, it [DCID] Cisco
produces the following output: Certified
Specialist. Q&A
is null? 1 and more
is an integer? 1
is a string? 1  CCNP Data
is a double? 1 Center 300-615
is boolean? 1 [DCIT] Cisco
is an array? 1 Certified
is numeric?
Specialist
is a resource?
is an array? 1  CCNP Data
Center 300-620
[DCACI]Data

https://itexamtools.com/building-web-applications-in-php/ 9/41
7/1/2021 Building Web Applications in PHP - ITEXAMTOOLS

When the $testing variable is declared in line 2, no value Center ACI


Implementation
is assigned to it, so when the variable is tested in line 3 to
see whether it is null (using is_null()), the result  Cisco Design Exam
is 1 (true). After this, values are assigned to $testing by 352-001
using the = sign before testing it with the  Cisco DevNet
Exams
appropriate is_* function. An integer, assigned to
 Cisco Certified
the $testing variable in line 5, is a whole or real number.
DevNet
In simple terms, you can think of a whole number as a Associate 200-
number without a decimal point. A string, assigned to 901 DEVASC
the $testing variable in line 8, is a collection of characters.
 Cisco Enterprise
When you work with strings in your scripts, they should Exams
always be surrounded by double or single quotation
 Cisco Field
marks (” or ‘). A double, assigned to the $testing variable Tech.Exams
in line 11, is a floating-point number (that is, a number  Cisco Security
that includes a decimal point). A Boolean, assigned to Exams
the $testing variable in line 14, can have one of two  Cisco Service
Provider Exams
special values: true or false. In line 17, an array is created
using the array() function, which you’ll learn more about  VMware
in Chapter 8, “Working with Arrays.” This particular array  VMware Cloud
contains three items, and the script dutifully Management and
Automation exams
reports $testing to have a type of “array.”
 VMware Data
From line 20 through the end of the script, no value is Center Virtualization
reassigned to $testing—only the type is tested. Lines 20  VMware Desktop
And Mobility
and 22 test whether $testing is a numeric or resource
type, respectively, and because it is not, no value is  VMware Network
Virtualization
displayed to the user. In line 24, the script tests again to
 VMware Digital
see whether $testing is an array, and because it is, the
Workspace
value of 1 is displayed.
 VMware Digital
Business
Changing Type with settype() Transformation

PHP also provides the function settype(), which is used to  About


change the type of a variable. To use settype(), you place  Contact Us
the variable to change and the type to change it to

https://itexamtools.com/building-web-applications-in-php/ 10/41
7/1/2021 Building Web Applications in PHP - ITEXAMTOOLS

between the parentheses and separate the elements with Posts


a comma, like this:
PHP Artifi
cial
settype($variabletochange, 'new type'); Intell
igence
Listing 5.2 converts the value 3.14 (a float) to each of the
four standard types examined in this chapter.
Which
progra
Listing 5.2. Changing the Type of a Variable mming where
with settype() langua to get
1: <?php
ge is Best
2: $undecided = 3.14;
3: echo "is ".$undecided." a double? ".is_double($und Importa Deep
4: settype($undecided, 'string');
nt to Learnin
5: echo "is ".$undecided." a string? ".is_string($und
6: settype($undecided, 'integer'); learn g
7: echo "is ".$undecided." an integer? ".is_integer($
first? Engine
8: settype($undecided, 'double');
9: echo "is ".$undecided." a double? ".is_double($und
er Jobs
10: settype($undecided, 'bool'); Thinking
11: echo "is ".$undecided." a boolean? ".is_bool($unde
about Where to
12: ?>
learning get Best

to code Deep
By the Way but not Learning

sure Engineer
Per the PHP Manual, “double” is returned in case of a Jobs
where to
float, and not simply “float”. Your eyes are not deceiving
start?
you.
One of
In each case, we use the appropriate is_* function to the most
confirm the new data type and to print the value of the common
7 skills
variable $undecided to the browser using echo. When we questions
employer
convert the string “3.14” to an integer in line 6, any we hear s of the
information beyond the decimal point is lost forever. is, “Which future will
be
That’s why $undecided contains 3 after we change it programm
looking
back to a double in line 8. Finally, in line 10, we ing for
convert $undecided to a Boolean. Any number other language
than 0 becomes true when converted to a Boolean. When is Futurepro

printing a Boolean in PHP, true is represented Important of your


CV by

https://itexamtools.com/building-web-applications-in-php/ 11/41
7/1/2021 Building Web Applications in PHP - ITEXAMTOOLS

as 1 and false is represented as an empty string, so in to learn learning


line 11, $undecided is printed as 1. first?” about the
skills
Put these lines into a text file called settype.php and
employers
place this file in your web server document root. When
of
you access this script through your web browser, it
tomorrow
produces the following output: Building will most
Web
is 3.14 a double? 1 likely be
Applicati
is 3.14 a string? 1 looking
is 3 an integer? 1
ons in
is 3 a double? 1 PHP for, and
is 1 a boolean? 1 the online
Learn
courses
Changing Type by Casting How a
you can
web
take to
The principal difference between using settype() to browser
train up.
change the type of an existing variable and changing type interacts
by casting is the fact that casting produces a copy, with a
leaving the original variable untouched. To change type web
through casting, you indicate the name of a data type, in server,
parentheses, in front of the variable you are copying. For request/re
example, the following line creates a copy of sponse 10 Steps
the $originalvar variable, with a specific type (integer) and cycle, to
a new name $newvar. The $originalvar variable will still including Adopting
be available, and will be its original type; $newvar is a Artificial
GET/POS
Intelligen
completely new variable. T/Redirect ce in
. an Business
$newvar = (integer) $originalvar
introducto
Artificial
Listing 5.3 illustrates changing data types through ry
Intelligenc
casting. understan
e is
ding of
Listing 5.3. Casting a Variable applied
Hypertext
1: <?php everywher
2: $undecided = 3.14; Markup
e now a
3: $holder = (double) $undecided; Language
4: echo "is ".$holder." a double? ".is_double($holder days and
5: $holder = (string) $undecided;
(HTML),
there are
6: echo "is ".$holder." a string? ".is_string($holder as well as

https://itexamtools.com/building-web-applications-in-php/ 12/41
7/1/2021 Building Web Applications in PHP - ITEXAMTOOLS

7: $holder = (integer) $undecided;


the basic many
8: echo "is ".$holder." an integer? ".is_integer($hol
9: $holder = (double) $undecided; syntax many new
10: echo "is ".$holder." a double? ".is_double($holder and data horizons
11: $holder = (boolean) $undecided;
12: echo "is ".$holder." a boolean? ".is_bool($holder) structures researche
13: echo "<hr/>"; of the rs are
14: echo "original variable type of $undecided: ";
15: echo gettype($undecided); // double PHP exploring.
16: ?> language, this is
variables, abut how

Listing 5.3 never actually changes the type of logic, the AI can

the $undecided variable, which remains a double iteration, be applied

throughout this script, as illustrated on line 15, where arrays, to the

the gettype() function is used to determine the type error business

of $undecided. handling, models


and successfu
By the Way superglob lly and
al improve
Despite its usage here, don’t use gettype() to test for a
variables, many
certain type because it can be slow and is likely to be
among stages of
deprecated in future versions. Use the is_* family of
other any
functions to test type in production. This usage is simply
elements business.
for illustrative purposes.

In fact, casting $undecided creates a copy that is then


converted to the type specified at the time of the cast,
Posts
and stored in the variable $holder. This casting occurs
first in line 3, and again in lines 5, 7, 9, and 11. Because data COMPTI
the code is working with only a copy of $undecided and scienc A A+
e
not the original variable, it never lost its original value, as
the $undecided variable did in line 6 of Listing 5.2 when
its type changed from a string to an integer. CompTI
How
A A+
Put the contents of Listing 5.3 into a text file HADOO
Practic
called casttype.php and place this file in your web server P is
e
document root. When you access this script through your useful
Questio
web browser, it produces the following output: to data
ns Core

https://itexamtools.com/building-web-applications-in-php/ 13/41
7/1/2021 Building Web Applications in PHP - ITEXAMTOOLS

is 3.14 a double? 1 scientis 1 (220-


is 3.14 a string? 1
is 3 an integer? 1 ts 1001)
is 3.14 a double? 1 and
is 1 a boolean? 1 Hadoop
original variable type of 3.14: double Core 2
allows the
(220-
Now that you’ve seen how to change the contents of a users to
1002)
variable from one type to another either by store all
using settype() or by casting, consider why this might be forms of Test your
useful. It is not a procedure that you will have to use often data, and knowledg
because PHP automatically casts your variables for you provides e with a
when the context of the script requires a change. massive free set of
However, such an automatic cast is temporary, and you storage test
might want to make a variable persistently hold a for any questions
particular data type—thus, the ability to specifically kind of from Com
change types. data.… pTIA A+
Practice
For example, the numbers that a user types into an Questions
HTML form will be made available to your script as the Exam
string type. If you try to add two strings together because Cram
they contain numbers, PHP will helpfully convert these Which Core 1
strings into numbers while the addition is taking place. So program
(220-
ming
"30cm" + "40cm" language 1001)…
is
results in an answer of 70. Important
to learn
By the Way first?

Thinking CompTIA
The generic term number is used here to mean integers
about A+
and floats. If the user input is in float form, and the strings Complete
learning
added together were “3.14cm” and “4.12cm”, the answer overview
to code
provided would be 7.26.
but not This guide
During the casting of a string into an integer or float, PHP sure helps you
will ignore any non-numeric characters. The string will be where to get a
truncated, and any characters from the location of the first start? better
non-numeric character onward are ignored. So, One of grasp of

https://itexamtools.com/building-web-applications-in-php/ 14/41
7/1/2021 Building Web Applications in PHP - ITEXAMTOOLS

whereas “30cm” is transformed into “30”, the the most what is


string “6ft2in” becomes just 6 because the rest of the common involved
string evaluates to zero. questions with
we hear studying
You might want to clean up the user input yourself and
is, “Which for the
use it in a particular way in your script. Imagine that the
programm CompTIA
user has been asked to submit a number. We can
ing A Plus
simulate this by declaring a variable and assigning the
language certificatio
user’s input to it:
is n exam.
$test = "30cm"; Important The
to learn CompTIA
As you can see, the user has added units to his number first?” A+
—instead of entering “30”, the user has entered “30cm”. certificatio
You can make sure that the user input is clean by casting n exam
it as an integer: has

$newtest = (integer) $test;


been..
echo "Your imaginary box has a width of $newtest centi
how to
Become a
The resulting output would be Facebook
Data
Your imaginary box has a width of 30 centimeters. Engineer
? just
Had the user input not been cast, and the value of the Start
original variable, $test, been used in place Here.
of $newtest when printing the statement regarding the
With over
width of a box, the result would have been
2.7 billion
Your imaginary box has a width of 30cm centimeters. active
monthly
This output looks strange; in fact, it looks like parroted users,
user input that hadn’t been cleaned up (which is exactly Facebook
what it is). is an
endless
Why Test Type? source of
big data. if
you have
https://itexamtools.com/building-web-applications-in-php/ 15/41
7/1/2021 Building Web Applications in PHP - ITEXAMTOOLS

Why might it be useful to know the type of a variable? the dream


There are often circumstances in programming in which to be a
data is passed to you from another source. In Chapter 7, Facebook
you will learn how to create functions in your scripts, and data
data is often passed between one or more functions engineer,
because they can accept information from calling code in you are at
the form of arguments. For the function to work with the the right
data it is given, it is a good idea to first verify that the place
function has been given values of the correct data type. here
For example, a function expecting data that has a type of
“resource” will not work well when passed a string.

Operators and Expressions


With what you have learned so far, you can assign data How to
to variables, and you can even investigate and change whizz
Your Next
the data type of a variable. A programming language isn’t
Remote
very useful, though, unless you can manipulate the data Interview
you have stored. Operators are symbols used to
Remote
manipulate data stored in variables, to make it possible to
interviews
use one or more values to produce a new value, or to
are now
check the validity of data to determine the next step in a
playing a
condition, and so forth. A value operated on by an
crucial
operator is referred to as an operand.
part in
By the Way today’s
job
An operator is a symbol or series of symbols that, when
market.
used in conjunction with values, performs an action and
Find out
usually produces a new value.
all the
An operand is a value used in conjunction with an most
operator. There are usually two or more operands to one important
operator. remote
interview
tips to

https://itexamtools.com/building-web-applications-in-php/ 16/41
7/1/2021 Building Web Applications in PHP - ITEXAMTOOLS

In this simple example, two operands are combined with give


an operator to produce a new value: yourself
all the
(4 + 5)
best
The integers 4 and 5 are operands. The addition operator chances
(+) operates on these operands to produce the integer 9. in
Operators almost always sit between two operands, succeedin
although you will see a few exceptions later in this g.
chapter.

The combination of operands with an operator to produce


a result is called an expression. Although operators and
their operands form the basis of expressions, an
expression need not contain an operator. In fact, an 7 skills
expression in PHP is defined as anything that can be employer
s of the
used as a value. This includes integer constants such
future will
as 654, variables such as $user, and function calls such be
as gettype(). The expression (4 + 5), for example, looking
consists of two expressions (4 and 5) and an operator for

(+). When an expression produces a value, it is often said Futurepro


to resolve to that value. That is, when all subexpressions of your
are taken into account, the expression can be treated as CV by
if it were a code for the value itself. In this case, the learning
expression (4 + 5) resolves to 9. about the
skills
By the Way
employers
An expression is any combination of functions, values, of
and operators that resolves to a value. As a rule of tomorrow
thumb, if you can use it as if it were a value, it is an will most
expression. likely be
looking
Now that you have the principles out of the way, it’s time
for, and
to take a tour of the operators commonly used in PHP
the online
programming.
courses

https://itexamtools.com/building-web-applications-in-php/ 17/41
7/1/2021 Building Web Applications in PHP - ITEXAMTOOLS

The Assignment Operator you can


take to
You have seen the assignment operator in use each time
train up.
a variable was declared in an example; the assignment
operator consists of the single character: =. The
assignment operator takes the value of the right-side
operand and assigns it to the left-side operand:

$name = "jimbo";
Data
The variable $name now contains the string “jimbo”. This science
construct is also an expression. Although it might seem at interview
preparati
first glance that the assignment operator simply changes on: How
the variable $name without producing a value, in fact, a to answer
statement that uses the assignment operator always top
questions
resolves to a copy of the value of the right operand. Thus
When it
echo $name = "jimbo";
comes to
prints the string “jimbo” to the browser while it also interview
assigns the value “jimbo” to the $name variable. preparatio
n, for data
Arithmetic Operators science
technical
The arithmetic operators do exactly what you would
savviness
expect—they perform arithmetic operations. Table 5.2
and
lists these operators along with examples of their usage
communic
and results.
ation skills
Table 5.2. Arithmetic Operators are of
equal
Operator Name Example Sample Result
importanc
+ Addition 10+3 13 e.
− Subtraction 10−3 7

/ Division 10/3 3.3333333333333

* Multiplication 10*3 30
Posts
% Modulus 10%3 1

https://itexamtools.com/building-web-applications-in-php/ 18/41
7/1/2021 Building Web Applications in PHP - ITEXAMTOOLS

The addition operator adds the right-side operand to the CISCO Featur
ed
left-side operand. The subtraction operator subtracts the
right-side operand from the left-side operand. The
division operator divides the left-side operand by the
right-side operand. The multiplication operator multiplies
CCNA How
the left-side operand by the right-side operand. The
200-301 HADOO
modulus operator returns the remainder of the left-side
(Cisco P is
operand divided by the right-side operand.
Certifie useful
d to data
The Concatenation Operator Networ scientis
k ts
The concatenation operator is represented by a single Associ
period (.). Treating both operands as strings, this operator ate) – Hadoop
appends the right-side operand to the left-side operand. Comple allows the
So te users to
store all
"hello"." world"
CCNA forms of
200-301 data, and
returns
(Cisco provides
"hello world" Certified massive
Network storage
Note that the resulting space between the words occurs
Associate for any
because there is a leading space in the second operand
)– kind of
(” world” instead of “world”). The concatenation operator
Complete data.…
literally smashes together two strings without adding any
The Cisco
padding. So, if you tried to concatenate two strings
Certified
without leading or trailing spaces, such as
Network
"hello"."world" Associate
(CCNA How to
you would get this as your result:
200-301) whizz
exam is a Your Next
"helloworld"
Remote
120- Interview
Regardless of the data types of the operands used with minute…
the concatenation operator, they are treated as strings, Remote
and the result will always be of the string type. You will What’s interviews
new in
https://itexamtools.com/building-web-applications-in-php/ 19/41
7/1/2021 Building Web Applications in PHP - ITEXAMTOOLS

encounter concatenation frequently throughout this book are now


when the results of an expression of some kind must be playing a
combined with a string, as in crucial
Packet part in
$cm = 212;
Tracer today’s
echo "the width is ".($cm/100)." meters";
7.3.1?
job
Combined Assignment Operators Cisco market.
Packet Find out
Although there is only one true assignment operator, PHP
Tracer all the
provides a number of combination operators that
7.3.1 has most
transform the left-side operand and return a result, while
already important
also modifying the original value of the variable. As a rule,
been remote
operators use operands but do not change their original
released! interview
values, but combined assignment operators break this
Current tips to
rule. A combined assignment operator consists of a
build is give
standard operator symbol followed by an equal sign.
Packet yourself
Combination assignment operators save you the trouble
Tracer all the
of using two operators in two different steps within your
7.3.1.036 best
script. For example, if you have a variable with a value of
2. Have a chances
4, and you want to increase this value to 4 more, you
look in
might see:
at Cisco succeedin
$x = 4; Packet… g.
$x = $x + 4; // $x now equals 8

However, you can also use a combination assignment


operator (+=) to add and return the new value, as shown
here:

$x = 4; How to Building
$x += 4; // $x now equals 8 whizz Web
Your Next Applicati
Each arithmetic operator, as well as the concatenation Remote ons in
Interview PHP
operator, also has a corresponding combination
assignment operator. Table 5.3 lists these new operators Remote Learn
and shows an example of their usage. interviews How a
are now web

https://itexamtools.com/building-web-applications-in-php/ 20/41
7/1/2021 Building Web Applications in PHP - ITEXAMTOOLS

Table 5.3. Some Combined Assignment playing a browser


Operators
crucial interacts
Operator Example Equivalent To part in with a
+= $x += 5 $x = $x + 5 today’s web
job server,
−= $x −= 5 $x = $x − 5
market. request/re
/= $x /= 5 $x = $x / 5
Find out sponse
*= $x *= 5 $x = $x * 5
all the cycle,
%= $x %= 5 $x = $x % 5 most including
.= $x .= ” test” $x = $x.” test” important GET/POS
remote T/Redirect
Each of the examples in Table 5.3 transforms the value
interview . an
of $x using the value of the right-side operand.
tips to introducto
Subsequent uses of $x will refer to the new value. For
give ry
example
yourself understan
$x = 4; all the ding of
$x += 4; // $x now equals 8 best Hypertext
$x += 4; // $x now equals 12
$x -= 3; // $x now equals 9 chances Markup
in Language
These operators will be used throughout the scripts in the succeedin (HTML),
book. You will frequently see the combined concatenation g. as well as
assignment operator when you begin to create dynamic the basic
text; looping through a script and adding content to a syntax
string, such as dynamically building the HTML code to and data
represent a table, is a prime example of the use of a structures
combined assignment operator. of the
CCNP PHP
Automatically Incrementing and Data
language,
Center
Decrementing an Integer Variable variables,
300-610
When coding in PHP, you will often find it necessary to [DCID] logic,
Describin iteration,
increment or decrement a variable that is an integer type.
g High
You will usually need to do this when you are counting the Availabilit arrays,
iterations of a loop. You have already learned two ways of y on error
Layer 2 handling,
and
https://itexamtools.com/building-web-applications-in-php/ 21/41
7/1/2021 Building Web Applications in PHP - ITEXAMTOOLS

doing this—either by incrementing the value of $x using In this superglob


the addition operator Learning al
session, variables,
$x = $x + 1; // $x is incremented by 1
we’ll be among
or by using a combined assignment operator looking at other
features elements
$x += 1; // $x is incremented by 1
of Cisco

In both cases, the new value is assigned to $x. Because network

expressions of this kind are common, PHP provides platforms

some special operators that allow you to add or subtract that

the integer constant 1 from an integer variable, assigning provide


for high Modeling
the result to the variable itself. These are known as Techniqu
the post-increment and post-decrement operators. The availability
es in
post-increment operator consists of two plus symbols , in this Predictive
case, high Analytics:
appended to a variable name:
availability Analytics
$x++; // $x is incremented by 1
and Data
at layer 2. Science
This expression increments the value represented by the
Thomas
variable $x by one. Using two minus symbols in the same
W. Miller
way will decrement the variable:
While
$x--; // $x is decremented by 1 earning a
Cisco degree in
If you use the post-increment or post-decrement CCNA philosoph
operators in conjunction with a conditional operator, the practice
y may not
test: Try
operand will be modified only after the first operation has be the
these 20
finished: exam best
questions
$x = 3; career
$y = $x++ + 3;
Use this move
CCNA (unless a
In this instance, $y first becomes 6 (the result of 3 + 3)
latest student…
and then $x is incremented.
practice
In some circumstances, you might want to increment or test as
Master of
decrement a variable in a test expression before the test study
Applied

https://itexamtools.com/building-web-applications-in-php/ 22/41
7/1/2021 Building Web Applications in PHP - ITEXAMTOOLS

is carried out. PHP provides the pre-increment and pre- material


decrement operators for this purpose. These operators to prepare
behave in the same way as the post-increment and post- for the
decrement operators, but they are written with the plus or Cisco Data
minus symbols preceding the variable: CCNA Science
Routing
++$x; // $x is incremented by 1 University
--$x; // $x is decremented by 1 and
of
Switching
Michigan
If these operators are used as part of a test expression, exam.
Online
incrementing occurs before the test is carried out. For With 20
Master
example, in the next fragment, $x is incremented before it questions
Degree
is tested against 4. …
Learn
$x = 3; from the
++$x < 4; // false
#1 public

The test expression returns false because 4 is not smaller research

than 4. university
in the
IP
Comparison Operators Routing U.S. and
in the join the
Comparison operators perform comparative tests using LAN next
their operands and return the Boolean value true if the generatio
Almost all
test is successful or false if the test fails. This type of n of data
enterprise
expression is useful when using control structures in your scientists.
networks
scripts, such as if and while statements. This book Completel
use
covers if and while statements in Chapter 6, “Flow y online.
VLANs.
Control Functions in PHP.”
To route
For example, to test whether the value contained in $x is IP
smaller than 5, you can use the less-than operator as part packets in
of your expression: and out of
those
$x < 5 CCNP
VLANs, Enterpris
If $x contains the value 3, this expression will have the some e
devices Advanced
value true. If $x contains 7, the expression resolves
Routing
to false. (either
ENARSI
https://itexamtools.com/building-web-applications-in-php/ 23/41
7/1/2021 Building Web Applications in PHP - ITEXAMTOOLS

Table 5.4 lists the comparison operators. routers or 300-410


Official
Layer 3
Table 5.4. Comparison Operators Cert
switches) Guide
Operator Name Returns Example Result need to
True If… ($x Is 4) have an CCNP

IP Enterprise
== Equivalence Left is $x == 5 false
address in Advanced
equivalent
to right each Routing

subnet ENARSI
!= Non- Left is not $x != 5 true
equivalence equivalent and have 300-410
to right a Official

=== Identical Left is $x === 4 true connected Cert


equivalent route to Guide.
to right each of Published
and they
those Mar 19,
are the 2020 by
subnets.
same Cisco
Then the
type
IP Press.
Non- Left is $x === false Part of the
addresses
equivalence equivalent “4”
on those Official
to right
routers or Cert
but they
Layer 3 Guide
are not
the same switches series.
type can serve
> Greater Left is $x > 4 false as the
than greater default
than right gateways
>= Greater Left is $x >= 4 true in those
than or greater subnets.
equal to than or
equal to
right

< Less than Left is $x < 4 false


less than
right

https://itexamtools.com/building-web-applications-in-php/ 24/41
7/1/2021 Building Web Applications in PHP - ITEXAMTOOLS

Operator Name Returns Example Result


True If… ($x Is 4)

<= Less than or Left is $x <= 4 true


equal to less than
or equal
to right

These operators are most commonly used with integers


or doubles, although the equivalence operator is also
used to compare strings. Be very sure to understand the
difference between the == and = operators.
The == operator tests equivalence, whereas
the = operator assigns value. Also, remember
that === tests equivalence with regards to both value and
type.

Creating Complex Test Expressions with


the Logical Operators
Logical operators test combinations of Boolean values.
For example, the or operator, which is indicated by two
pipe characters (||) or simply the word or, returns the
Boolean value true if either the left or the right operand is
true:

true || false

This expression returns true.

The and operator, which is indicated by two ampersand


characters (&&) or simply the word and, returns the
Boolean value true only if both the left and right operands
are true:

true && false

This expression returns the Boolean value false. It’s


unlikely that you will use a logical operator to test
https://itexamtools.com/building-web-applications-in-php/ 25/41
7/1/2021 Building Web Applications in PHP - ITEXAMTOOLS

Boolean constants because it makes more sense to test


two or more expressions that resolve to a Boolean. For
example

($x > 2) && ($x < 15)

returns the Boolean value true if $x contains a value that


is greater than 2 and smaller than 15. Parentheses are
used when comparing expressions to make the code
easier to read and to indicate the precedence of
expression evaluation. Table 5.5 lists the logical
operators.

Table 5.5. Logical Operators

Operator Name Returns Example Result


True If…

|| Or Left or right true || true


is true false

or Or Left or right true or true


is true false

xor Xor Left or right true xor false


is true but true
not both

&& And Left and true && false


right are false
true

and And Left and true and false


right are false
true

! Not The single ! true false


operand is
not true

You might wonder why are there two versions of both


the or and the and operators, and that’s a good question.

https://itexamtools.com/building-web-applications-in-php/ 26/41
7/1/2021 Building Web Applications in PHP - ITEXAMTOOLS

The answer lies in operator precedence, which you will


examine next.

Operator Precedence
When you use an operator within an expression, the PHP
engine usually reads your expression from left to right.
For complex expressions that use more than one
operator, though, the PHP engine could be led astray
without some guidance. First, consider a simple case:

4 + 5

There’s no room for confusion here—PHP simply


adds 4 to 5. But what about the following fragment, with
two operators:

4 + 5 * 2

This presents a problem. Should PHP find the sum


of 4 and 5, and then multiply it by 2, providing the
result 18? Or does it mean 4 plus the result of 5 multiplied
by 2, resolving to 14? If you were simply to read from left
to right, the former would be true. However, PHP attaches
different precedence to different operators, and because
the multiplication operator has higher precedence than
the addition operator, the second solution to the problem
is the correct one: 4 plus the result of 5 multiplied by 2.

However, you can override operator precedence by


putting parentheses around your expressions. In the
following fragment, the addition expression will be
evaluated before the multiplication expression:

(4 + 5) * 2

Whatever the precedence of the operators in a complex


expression, it is a good idea to use parentheses to make

https://itexamtools.com/building-web-applications-in-php/ 27/41
7/1/2021 Building Web Applications in PHP - ITEXAMTOOLS

your code clearer and to save you from bugs such as


applying sales tax to the wrong subtotal in a shopping
cart situation. The following is a list of the operators
covered in this chapter in precedence order (those with
highest precedence are listed first):

++, –, (cast)

/, *, %

+, –

<, <=, =>, >

==, ===, !=

&&

||

=, +=, -=, /=, *=, %=, .=

and

xor

or

As you can see, or has a lower precedence than ||,


and and has a lower precedence than &&, so you can
use the lower-precedence logical operators to change the
way a complex test expression is read. In the following
fragment, the two expressions are equivalent, but the
second is much easier to read:

$x and $y || $z

$x && ($y || $z)

Taking it one step further, the following fragment is easier


still:

$x and ($y or $z)

However, all three examples are equivalent.

https://itexamtools.com/building-web-applications-in-php/ 28/41
7/1/2021 Building Web Applications in PHP - ITEXAMTOOLS

The order of precedence is the only reason that


both && and and are available in PHP. The same is true
of || and or. In most circumstances, the use of
parentheses makes for clearer code and fewer bugs than
code that takes advantage of the difference in the
precedence of these operators. This book will tend to use
the more common || and && operators and rely on
parenthetical statements to set specific operator
precedence.

Along with this basic PHP coding skills,

SKILLS YOU NEED TO GAIN


Building Web Applications in PHP
Hypertext Preprocessor (PHP)

Html

Cascading Style Sheets (CCS)

Expanding each of them,

Introduction to Dynamic Web Content: the basic


structure of a web application and how a web browser
interacts with a web server. We explore the Request-
Response Cycle that is the basis of the Hypertext
Transfer Protocol (HTTP).

HyperText Markup Language (HTML) : the basics of the


HyperText Markup Language (HTML) that is the markup
for web pages.

Cascading Style Sheets (CSS) : the basics of cascading


Style Sheets (CSS) that allow us to style the markup for
web pages.

https://itexamtools.com/building-web-applications-in-php/ 29/41
7/1/2021 Building Web Applications in PHP - ITEXAMTOOLS

Installing PHP and SQL : The first technical task is to


work through the installation steps including installing a
text editor, installing MAMP or XAMPP (or equivalent),
creating a MySql Database, and writing a PHP program.

Introduction to PHP : We begin learning PHP

PHP Arrays : unique aspects of arrays in the PHP


language.

PHP Functions : unique aspects of functions in PHP.

PHP and HTML Forms : how HTML forms are created


and processed in the PHP language.

Introducing to a course for


Building Web Applications in PHP
By University of Michigan
This course is part of the Web Applications for Everybody
Specialization

A course by Charles Russell Severance and having 4.8


ratings and 458 reviews!

In this course, you’ll explore the basic structure of a web


application, and how a web browser interacts with a web
server. You’ll be introduced to the request/response cycle,
including GET/POST/Redirect. You’ll also gain an
introductory understanding of Hypertext Markup
Language (HTML), as well as the basic syntax and data
structures of the PHP language, variables, logic, iteration,
arrays, error handling, and superglobal variables, among
other elements. An introduction to Cascading Style
Sheets (CSS) will allow you to style markup for
webpages. Lastly, you’ll gain the skills and knowledge to

https://itexamtools.com/building-web-applications-in-php/ 30/41
7/1/2021 Building Web Applications in PHP - ITEXAMTOOLS

install and use an integrated PHP/MySQL environment


like XAMPP or MAMP.

And along with that, you will learn


everything that explained earlier in this
class above.

University of Michigan

The mission of the University of Michigan is to serve the


people of Michigan and the world through preeminence in
creating, communicating, preserving and applying
knowledge, art, and academic values, and in developing
leaders and citizens who will challenge the present and
enrich the future.

Enrollment options
you can Enroll this course for FREE and can learn totally
free for next 7 days and if you feel it is worth to enhance
your knowledge and career, you can go further for getting
the certification.

Start FREE Learning Today


for 7 days.

Financial aid available


This Course Plus the Full Specialization

Shareable Certificates

Self-Paced Learning Option

https://itexamtools.com/building-web-applications-in-php/ 31/41
7/1/2021 Building Web Applications in PHP - ITEXAMTOOLS

Course Videos & Readings

Practice Quizzes

Graded Assignments with Peer Feedback

Graded Quizzes with Feedback

Graded Programming Assignments

63,451 already enrolled already.

Let us continue the Free lesson here giving you


more Idea about the course.

PHP Constants
Variables offer a flexible way of storing data because you
can change their values and the type of data they store at
any time during the execution of your scripts. However, if
you want to work with a value that must remain
unchanged throughout your script’s execution, you can
define and use a constant. You must use PHP’s built-
in define() function to create a constant, which
subsequently cannot be changed unless you
specifically define() it again. To use the define() function,
place the name of the constant and the value you want to
give it, within parentheses and separated by a comma:

define("YOUR_CONSTANT_NAME", 42);

The value you want to set can be a number, a string, or a


Boolean. By convention, the name of the constant should
be in capital letters. Constants are accessed with the
constant name only; no dollar symbol is required. Listing
5.4 shows you how to define and access a constant.

https://itexamtools.com/building-web-applications-in-php/ 32/41
7/1/2021 Building Web Applications in PHP - ITEXAMTOOLS

Listing 5.4. Defining and Accessing a Constant


1: <?php
2: define("THE_YEAR", "2008");
3: echo "It is the year ".THE_YEAR;
4: ?>

Did You Know

Constants can be used anywhere in your scripts,


including in functions stored in external files.

Notice that in line 3 the concatenation operator is used to


append the value held by the constant to the string “It is
the year ” because PHP does not distinguish between a
constant and a string within quotation marks.

Put these few lines into a text file called constant.php and
place this file in your web server document root. When
you access this script through your web browser, it
produces the following output:

It is the year 2008

The define() function can also accept a third Boolean


argument that determines whether the constant name
should be case sensitive. By default, constant names are
case sensitive. However, by passing true to
the define() function, you can change this behavior, so if
you were to set up our THE_YEAR constant as

define("THE_YEAR", "2008", true);

you could access its value without worrying about case:

echo the_year;
echo ThE_YeAr;
echo THE_YEAR;

The preceding three expressions are equivalent, and all


would result in an output of 2008. This feature can make

https://itexamtools.com/building-web-applications-in-php/ 33/41
7/1/2021 Building Web Applications in PHP - ITEXAMTOOLS

scripts a little friendlier for other programmers who work


with our code because they will not need to consider case
when accessing a constant we have already defined. On
the other hand, given the fact that other
constants are case sensitive, this might make for more,
rather than less, confusion as programmers forget which
constants to treat in which way. Unless you have a
compelling reason to do otherwise, the safest course is to
keep your constants case sensitive and define them
using uppercase characters, which is an easy-to-
remember (not to mention standard) convention.

Predefined Constants
PHP automatically provides some built-in constants for
you. For example, the constant __FILE__ returns the
name of the file that the PHP engine is currently reading.
The constant __LINE__ returns the current line number of
the file. These constants are useful for generating error
messages. You can also find out which version of PHP is
interpreting the script with the PHP_VERSION constant.
This constant can be useful if you need version
information included in script output when sending a bug
report.

Summary
This chapter covered some of the basic features of the
PHP language. You learned about variables and how to
assign values to them using the assignment operator, as
well as received an introduction to the scope of variables
and built-in superglobals. You got an introduction to
operators and learned how to combine some of the most
common of these into expressions. Finally, you learned
how to define and access constants.

https://itexamtools.com/building-web-applications-in-php/ 34/41
7/1/2021 Building Web Applications in PHP - ITEXAMTOOLS

Now that you have mastered some of the fundamentals


of PHP, the next chapter will really put you in the driver’s
seat. You will learn how to make scripts that can make
decisions and repeat tasks, with help from variables,
expressions, and operators.

Q&A
Q. Why is it useful to know the type of data that a
variable holds?

A. Often the data type of a variable constrains what you


can do with it. For example, you can’t perform array-
related functions on simple strings. Similarly, you
might want to make sure that a variable contains an
integer or a float before using it in a mathematical
calculation, even though PHP will often help you by
changing data types for you in this situation.

Q. Should I obey any conventions when naming


variables?

A. Your goal should always be to make your code easy to


read and understand. A variable such
as $ab123245 tells you nothing about its role in your
script and invites typos. Keep your variable names
short and descriptive.A variable named $f is unlikely to
mean much to you when you return to your code after
a month or so. A variable named $filename, on the
other hand, should make more sense.

Q. Should I learn the operator precedence table?

A. There is no reason you shouldn’t, but I would save the


effort for more useful tasks. By using parentheses in
your expressions, you can make your code easy to
read while defining your own order of precedence.

Workshop

https://itexamtools.com/building-web-applications-in-php/ 35/41
7/1/2021 Building Web Applications in PHP - ITEXAMTOOLS

The workshop is designed to help you anticipate possible


questions, review what you’ve learned, and begin putting
your knowledge into practice.

Quiz
1. Which of the following variable names are not valid?
$a_value_submitted_by_a_user $666666xyz
$xyz666666 $_____counter_____ $the first $file-name

2. What will the following code fragment output?$num =


33; (boolean) $num; echo $num;

3. What will the following statement output?echo


gettype(“4”);

4. What will be the output from the following code


fragment?$test_val = 5.5466; settype($test_val,
“integer”); echo $test_val;

5. Which of the following statements does not contain an


expression?4; gettype(44); 5/12;

6. Which of the statements in question 5 contains an


operator?

7. What value will the following expression return?5 <


2What data type will the returned value be?

Answers
1. The variable name $666666xyz is not valid because it
does not begin with a letter or an underscore
character. The variable name $the first is not valid
because it contains a space. $file-name is also invalid
because it contains a nonalphanumeric character (-).

2. The fragment will print the integer 33. The cast to


Boolean produces a converted copy of the value
stored in $num. It does not alter the value actually
stored there.

3. The statement will output the string “string”.

4. The code will output the value 5. When a float is

https://itexamtools.com/building-web-applications-in-php/ 36/41
7/1/2021 Building Web Applications in PHP - ITEXAMTOOLS

converted to an integer, any information beyond the


decimal point is lost.

5. They are all expressions because they all resolve to


values.

6. The statement 5/12; contains a division operator.

7. The expression will resolve to false, which is a


Boolean value.

Activities
1. Create a script that contains at least five different
variables. Populate them with values of different data
types and use the gettype() function to print each type
to the browser.

2. Assign values to two variables. Use comparison


operators to test whether the first value isThe same as
the secondLess than the secondGreater than the
secondLess than or equal to the secondPrint the result
of each test to the browser.Change the values
assigned to your test variables and run the script
again.

More Titles to Refer for Learning & Building Web


Applications in PHP

https://itexamtools.com/building-web-applications-in-php/ 37/41
7/1/2021 Building Web Applications in PHP - ITEXAMTOOLS

Leave a comment  Building Web Applications in PHP

Read More Posts

How Which How to Modeling


HADOOP is programming whizz Your Techniques
useful to language is Next in Predictive
data Important to Remote Analytics:
scientists learn first? Interview Analytics
and Data
Hadoop Thinking Remote Science

allows the about interviews Thomas W.


users to learning to are now Miller While
store all code but not playing a earning a
forms of sure where crucial part degree in
data, and to start? in today’s philosophy
provides One of the job market. may not be
massive most Find out all the best
storage for common the most career move
any kind of questions important (unless a
data. It can we hear is, remote student
handle a “Which interview plans to
large programmin tips to give teach
amount of g language yourself all philosophy,
tasks, but is Important the best and few of
here the… to learn chances in these
first?” succeeding.

https://itexamtools.com/building-web-applications-in-php/ 38/41
7/1/2021 Building Web Applications in PHP - ITEXAMTOOLS

positions are
available),…

Master of CCNP
Applied Data Enterprise
Science Advanced
Routing
University of ENARSI
300-410
Michigan Official Cert
Guide
Online
Master CCNP
Degree Enterprise
Learn from Advanced
the #1 public Routing
research ENARSI
university in 300-410
the U.S. and Official Cert
join the next Guide.
generation Published
of data Mar 19,
scientists. 2020 by
Completely Cisco Press.
online. Part of the
Official Cert
Guide
series.

Leave a Reply

Logged in as success. Log out?

Comment
https://itexamtools.com/building-web-applications-in-php/ 39/41
7/1/2021 Building Web Applications in PHP - ITEXAMTOOLS

Post Comment

This site uses Akismet to reduce spam. Learn how your comment
data is processed.

Recent Posts Latest design &


Attractions shape world-
class videos
Udemy Budget
Affordable
Discount sale
2021 Effe Agil
iOS
ctive Prog e
Discovery Dojo: Pyth ram Ga
on min me
The School Of g Dev
elop design & shape
Getting To Know men
t
world-class videos
Yourself

A Hands-On Guide
to Splunk
Enterprise Security Dev VCP
Ops 6- Sec
for DCV urity
Apache Kafka For VM Offic +
war ial SY0
Absolute e Cert -401
Beginners Adm Guid
inistr e
ator
Hadoop Developer s
Course with
MapReduce and
Java

Google BigQuery
& PostgreSQL :
Big Query for Data
Analysis

https://itexamtools.com/building-web-applications-in-php/ 40/41
7/1/2021 Building Web Applications in PHP - ITEXAMTOOLS

Learn Ethical
Hacking -CEHv10
from scratch

© 2021 ITEXAMTOOLS. All Rights Reserved. || The TREAD MARKS used in the website are the tread marks of the respective
site owners. ||
Sitemap  Disclosure  Privacy Policy  TOS

https://itexamtools.com/building-web-applications-in-php/ 41/41

You might also like