0% found this document useful (0 votes)
38 views35 pages

PHP Syntax and Basics Explained

Php

Uploaded by

pelumiemanuel13
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)
38 views35 pages

PHP Syntax and Basics Explained

Php

Uploaded by

pelumiemanuel13
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

CSC 102

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 of 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*/?>


<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 also gets around the FrontPage problems,
it can be cumbersome in certain situations, such as quick pop-in variable replacement. In
particular, 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 fairly sizable blocks of PHP code.

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


(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 [Link] 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.

<? ?>

Classwork: Hello world program


Now we’re ready to write our first PHP program. Open a new file in Dreamweaver and type:
<HTML>
<HEAD>
<TITLE>My first PHP program</TITLE>
</HEAD>
<BODY>
<?php
print(“Hello, world<BR><BR>\n”);
phpinfo();
?>
</BODY>
</HTML>

To save the file, create a folder called “Assignment” in the www directory of your Wamp folder,
save the file as [Link] in the assignment folder that you have created in the www
directory of your Wamp folder. To test your program, start the WampServer and go to localhost
(See Fig 2.2 above), in “Your Projects” section click on Assignment folder and click
helloworld.

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.

The closing php tag can be used as instruction termination, making the following block of code
an option as long as 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 of 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. 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. 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
/* 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:

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


<?php
Echo “Come on board!”;
?>
<?php

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

?>

UNIT 3- PHP BASICS

PHP Output Statement

PHP gives two options to choose between in order 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

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?";

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 over and over again, 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 as long as they abide by
the following basic rules:

[Link] 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 numbers.
4. Variables do not need to be declared before they are used.
5. The value of a variable is the value of its most recent assignment.
6. 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 in order 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..

If the whole point (why variables?!) is still fuzzy, don't worry, it will clear up quickly as we
progress. In the meantime, don't forget to terminate each variable declaration with the ever-trusty
semicolon!

PHP Data Types

Let’s take a 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, Such As This Statement
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
Object Compound Programmer-Defined Classes
Hold References to External Resources (Database
Resource Special
Connections, Etc.)
NULL Special Has Only One Possible Value: NULL

Variable Scope: Scope is the technical term for the rules about when a name (say, a variable or
function) has the same meaning in two different places and in what situations two names spelled
exactly the same way can actually refer to different things.
The scope of a variable is the part of the script where the variable can be referenced or used. PHP
has three different variable scopes namely:
 Local
 Global
 Static

A variable declared outside a function has a global scope and can only be accessed outside a
function. However, a variable declared within a function has a local scope and can only be
accessed within that function.

Example:
<?php
$x=5; // global scope
function myTest()
{
$y=10; // local scope
echo "<p>Test variable inside the function:<p>";
echo "Variable x is: $x";
echo "<br>";
echo "Variable y is: $y:";
}
myTest();
echo "<p>Test variable outside the function:<p>";
echo "Variable x is: $x";
echo "<br>";
echo "Variable y is: $y:";
?>

In the example above, there are two variables $x and $y and a function myTest(). $x is a global
variable declared outside the function and $y is a local variable since it is created inside the
function.

When we output the values of the two variables inside the myTest() function, it prints the value
of $y declared, but cannot print the value of $x since it is created outside the function.

Then, when we output the values of the two variables outside the myTest() function, it prints the
value of $x , but cannot print the value of $y since it is a local variable and it is created inside the
myTest() function.
Unless you make a special declaration in a function, that function won’t have access to the global
variables defined outside the function, even when they are defined in the same file. The global
keyword is used to access a global variable from within a function and is used before the
variables inside the function.

Example
<?php
$x=5; // global scope
$Y=10; //global scope
function myTest()
{
Global $x, $y;
$y=$x+$y;
}
myTest();
echo $y; // outputs 15
?>

PHP also store all global variables in an array called $GLOBALS[index]. The index holds the
name of the variable. This array is also accessible from within functions and can be used to
update global variables directly.

Example

<?php
$x=5; // global scope
$Y=10; //global scope
function myTest()
{
$GLOBALS[‘y’]= $GLOBALS[‘x’]+ $GLOBALS[‘y’];
}
myTest();
echo $y; // outputs 15
?>

PHP Static keyword


Normally, when a function is completed/executed, all of its variables are deleted. However,
sometimes we want a local variable NOT to be deleted because we need it for a further job.
To do this, we use the static keyword when the variable is first declared.

Example

<?php
function myTest()
{
static $x=0;
echo $x;
$x++;
}
myTest();
myTest();
myTest();
?>

Then, each time the function is called, the variable will still have the information it contained
from the last time the function was called.
NOTE: The variable is still local to the function.

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()
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.

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 Operator

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

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

Operato
Description
r
= Assigns A Value

<?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).

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.

Operato
Description
r
. Concatenates (Links) Two Strings Together
.= Adds A String Onto the End of An Existing String
<?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?

Operato
Description
r
+ 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;

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.

Operato
Description
r
+= 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:

<?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.

Operato
Description
r
++ 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

?>

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.

Operato
Description Example
r
== Is Equal To 3==2 (Will Return "False")
!= Is Not Equal To 3!=2 (Will Return "True")
<> Is Not Equal To 3<>2 (Will Return "True")
> 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.

Operato
Meaning Description
r
&& And True If Two Statements Are True, Otherwise False
|| 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;


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,
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 numbers variable is greater than 3, echo that the
condition is met. Since this particular condition is true, the action will be performed.

Conditions are not at all limited to comparing numerical values.

<?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?";

$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!

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") {

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

<?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 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++;
}

?>

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++;

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

<?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!

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

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

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.

You might also like