Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
41 views

Chapter 1 - Expressions and Control Statements in PHP

Uploaded by

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

Chapter 1 - Expressions and Control Statements in PHP

Uploaded by

small.things1212
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 61

Chapter 1:

Expressions and Control Statements in PHP


PHP :

● PHP is Open source server-side programming/ scripting language that is especially


suited for web development and can be embedded into HTML.It is used to manage
dynamic content, databases, session tracking, even build entire e-commerce sites.
● PHP stands for Hypertext Preprocessor but its original name, Personal Home
Page.
● It was originally created by Rasmus Lerdorf in 1994.
● PHP runs on various platforms Windows, LINUX, Unix, Mac OS, etc.
● PHP is compatible with almost all server Apache, IIS(Internet Information Services) etc.
● PHP file extension .php
PHP Syntax :
● Basic PHP Syntax
● A PHP script can be placed anywhere in the document.
● A PHP script starts with <?php and ends with ?>:
Opening Markup/
● <?php Opening Tag
// PHP code goes here
Closing Markup/
?> Closing Tag

● The default file extension for PHP files is ".php".


● A PHP file normally contains HTML tags, and some PHP scripting code.
● Note: PHP statements end with a semicolon (;).
● Example :

<?php
echo "Hello World!";
?>
● PHP Case Sensitivity
● In PHP, keywords (e.g. if, else, while, echo, etc.), classes, functions, and user-
defined functions are not case-sensitive.
Advantages of PHP
Following are the advantages of php which are as follows:
1. Open Source
2. Platform Independent
3. Simple and Easy -The one who knows any programming language can easily work on PHP. It is simple to learn, as its
learning curve is not large. The syntax is simple and flexible to use.
4. Database- PHP is easily connected with the database and make the connection securely with databases. It has a built-in
module that is used to connect to the database easily.
5. Fast- PHP applications can be easily loaded over the slow Internet and data speed.
6. Maintenance- PHP has great online support and community, which helps the new developers to help in writing the code
and developing the web applications.
7. Security -PHP frameworks built-in feature and tools make it easier to protect the web applications from the outer attacks and
security threats.
PHP Comments
● Single line comment : two slashes // or hash symbol #
● For Example :
<?php
// This is a single-line comment

# This is also a single-line comment


echo “Hello World”;
?>
● Multiple-line comments : start the comment with a slash followed by asterisk
(/*) and end the comment with an asterisk followed by a slash (*/)
● For Example :
<?php
/*
This is a multiple-lines comment block
that spans over multiple
lines
*/
echo “Hello World”;
?>
PHP Variables
A variable can have a short name (like x and y) or a more descriptive name (age, carname,
total_volume).
Rules for PHP variables:
● A variable starts with the $ sign, followed by the name of the variable
● A variable name must start with a letter or the underscore character
● A variable name cannot start with a number
● A variable name can only contain alpha-numeric characters and underscores (A-z, 0-
9, and _ )
● Variable names are case-sensitive ($age and $AGE are two different variables)
Remember that PHP variable names are case-sensitive!
Example
<?php
$txt = "W3Schools.com";
echo "I love $txt!";
?>
PHP Variables Scope :

In PHP, variables can be declared anywhere in the script.


The scope of a variable is the part of the script where the variable can be referenced/used.
PHP has three different variable scopes:
● local
● global
● static
Global and Local Scope
A variable declared outside a function has a GLOBAL SCOPE and can only be accessed
outside a function:
Example
Variable with global scope:
Output :
<?php Variable x inside function is:
$x = 5; // global scope Variable x outside function is: 5

function myTest() {
// using x inside this function will generate an error
echo "<p>Variable x inside function is: $x</p>";
}
myTest();

echo "<p>Variable x outside function is: $x</p>";


?>
Global Keyword
● If we want to access data outside a function from code inside a function we
have to use global keyword within the function.
● For eg:
<?php
$x = 5; Output :
$y = 10; 15

function myTest() {
global $x, $y;
$y = $x + $y;
}
myTest(); // run function
echo $y; // output the new value for variable $y
?>
LOCAL SCOPE

A variable declared within a function has a LOCAL SCOPE and can only be accessed
within that function:
Example
Variable with local scope:
Output :
<?php
function myTest() { Variable x inside function is: 5
$x = 5; // local scope
Variable x outside function is:
echo "<p>Variable x inside function is: $x</p>";
}
myTest();

// using x outside the function will generate an error


echo "<p>Variable x outside function is: $x</p>";
?>
PHP The 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. We need it for a further
job.
To do this, use the static keyword when you first declare the variable:
Example
<?php
function myTest() {
static $x = 0; Output ;
echo $x; 012
$x++;
}

myTest();
myTest();
myTest();
?>
PHP Constants

● A constant is an identifier (name) for a simple value. The value cannot be changed
during the script.
● A valid constant name starts with a letter or underscore (no $ sign before the constant
name).

● Note: Unlike variables, constants are automatically global across the entire script.
Create a PHP Constant
To create a constant, use the define() function.
Syntax
define(name, value, case-insensitive)
Parameters:
name: Specifies the name of the constant
value: Specifies the value of the constant
case-insensitive: Specifies whether the constant name should be case-insensitive.
Default is false
Example : Create a constant with a case-sensitive name: Output :
<?php Welcome to W3Schools.com!
define("GREETING", "Welcome to W3Schools.com!");
echo GREETING;
?>
Example : Create a constant with a case-insensitive name:
<?php
// case-insensitive constant name Output :
define("GREETING", "Welcome to W3Schools.com!", true); Welcome to W3Schools.com!
echo greeting;
PHP Constant Arrays
In PHP7, you can create an Array constant using the define() function.

Example
Create an Array constant:

<?php
define("cars", [
"Alfa Romeo",
"BMW",
"Toyota"
]);
echo cars[0];
?>

Constants are Global


Constants are automatically global and can be used across the entire script.
PHP echo and print Statements :

PHP echo and print Statements


echo and print are more or less the same. They are both used to output data to the screen.
The differences are small:
●echo has no return value while print has a return value of 1 so it can be used in
expressions.
●echo can take multiple parameters (although such usage is rare) while print can take one
argument.
●echo is marginally faster than print.
The PHP echo Statement

The echo statement can be used with or without parentheses: echo or echo().
Display Text
The following example shows how to output text with the echo command (notice that the
text can contain HTML markup):
Example Output:
<?php PHP is Fun!
echo "<h2>PHP is Fun!</h2>"; Hello world!
echo "Hello world!<br>"; I'm about to learn PHP!
echo "I'm about to learn PHP!<br>"; This string was made with multiple parameters.
echo "This ", "string ", "was ", "made ", "with multiple parameters.";
?>
The PHP print Statement

The print statement can be used with or without parentheses: print or print().
Display Text
The following example shows how to output text with the print command (notice that the
text can contain HTML markup):
Example
<?php Output:
print "<h2>PHP is Fun!</h2>";
print "Hello world!<br>"; PHP is Fun!
print "I'm about to learn PHP!"; Hello world!
?> I'm about to learn PHP!
PHP Data Types

Variables can store data of different types, and different data types can do different things.
PHP supports the following data types:
● String
● Integer
● Float (floating point numbers - also called double)
● Boolean
● Array
● Object
● NULL
● Resource
PHP String

A string is a sequence of characters, like "Hello world!".


A string can be any text inside quotes. You can use single or double quotes:
Example
<?php
$x = "Hello world!";
$y = 'Hello world!';

echo $x;
echo "<br>";
echo $y;
?>
PHP Integer
An integer data type is a non-decimal number between -2,147,483,648 and 2,147,483,647.
Rules for integers:
● An integer must have at least one digit
● An integer must not have a decimal point
● An integer can be either positive or negative
● Integers can be specified in: decimal (base 10), hexadecimal (base 16), octal (base 8),
or binary (base 2) notation
In the following example $x is an integer. The PHP var_dump() function returns the data
type and value:
Example
<?php
$x = 5985;
var_dump($x);
?>
PHP Float

A float (floating point number) is a number with a decimal point or a number in


exponential form.
In the following example $x is a float. The PHP var_dump() function returns the data type
and value:
Example
<?php
$x = 10.365;
var_dump($x);
?>
A float is a number with a decimal point or a number in exponential form.
2.0, 256.4, 10.358, 7.64E+5, 5.56E-5 are all floats.
The float data type can commonly store a value up to 1.7976931348623E+308 (platform
dependent), and have a maximum precision of 14 digits.
PHP Boolean

A Boolean represents two possible states: TRUE or FALSE.


$x = true;
$y = false;
Booleans are often used in conditional testing.
PHP Array

An array stores multiple values in one single variable.


In the following example $cars is an array. The PHP var_dump() function returns the data
type and value:
Example
<?php
$cars = array("Volvo","BMW","Toyota");
var_dump($cars);
?>
PHP NULL Value

Null is a special data type which can have only one value: NULL.
A variable of data type NULL is a variable that has no value assigned to it.
Tip: If a variable is created without a value, it is automatically assigned a value of NULL.
Variables can also be emptied by setting the value to NULL:
Example
<?php
$x = "Hello world!";
$x = null;
var_dump($x);
?>
Resource

The special resource type is not an actual data type. It is the


storing of a reference to functions and resources external to PHP.

A common example of using the resource data type is a database


call.
PHP Operators

Operators are used to perform operations on variables and values.


PHP divides the operators in the following groups:
● Arithmetic operators
● Assignment operators
● Comparison operators
● Increment/Decrement operators
● Logical operators
● String operators
● Array operators
● Conditional assignment operators
PHP Arithmetic Operators
The PHP arithmetic operators are used with numeric values to perform common
arithmetical operations, such as addition, subtraction, multiplication etc.

Operator Name Example Result

+ Addition $x + $y Sum of $x and $y

- Subtraction $x - $y Difference of $x and $y

* Multiplication $x * $y Product of $x and $y

/ Division $x / $y Quotient of $x and $y

% Modulus $x % $y Remainder of $x divided by


$y

** Exponentiation $x ** $y Result of raising $x to the


$y'th power
PHP Assignment Operators
The PHP assignment operators are used with numeric values to write a value to a variable.
The basic assignment operator in PHP is "=". It means that the left operand gets set to the
value of the assignment expression on the right.
Assignment Same as... Description
x=y x=y The left operand gets set to the value of
the expression on the right
x += y x=x+y Addition
x -= y x=x-y Subtraction
x *= y x=x*y Multiplication
x /= y x=x/y Division
x %= y x=x%y Modulus
PHP Comparison Operators
The PHP comparison operators are used to compare two values (number or string):
Operator Name Example Result

== Equal $x == $y Returns true if $x is equal to $y

=== Identical $x === $y Returns true if $x is equal to $y, and they are of the same type

!= Not equal $x != $y Returns true if $x is not equal to $y

<> Not equal $x <> $y Returns true if $x is not equal to $y

!== Not identical $x !== $y Returns true if $x is not equal to $y, or they are not of the same type

> Greater than $x > $y Returns true if $x is greater than $y

< Less than $x < $y Returns true if $x is less than $y

>= Greater than or equal to $x >= $y Returns true if $x is greater than or equal to $y

<= Less than or equal to $x <= $y Returns true if $x is less than or equal to $y
PHP Increment / Decrement Operators
The PHP increment operators are used to increment a variable's value.
The PHP decrement operators are used to decrement a variable's value.

Operator Name Description

++$x Pre-increment Increments $x by one,


then returns $x

$x++ Post-increment Returns $x, then


increments $x by one

--$x Pre-decrement Decrements $x by one,


then returns $x

$x-- Post-decrement Returns $x, then


decrements $x by one
PHP Logical Operators
The PHP logical operators are used to combine conditional statements.

Operator Name Example Result


and And $x and $y True if both $x and $y are true
or Or $x or $y True if either $x or $y is true
xor Xor $x xor $y True if either $x or $y is true, but not
both
&& And $x && $y True if both $x and $y are true
|| Or $x || $y True if either $x or $y is true
! Not !$x True if $x is not true
PHP String Operators

PHP has two operators that are specially designed for strings.

Operator Name Example Result


. Concatenation $txt1 . $txt2 Concatenation of $txt1
and $txt2
.= Concatenation $txt1 .= $txt2 Appends $txt2 to $txt1
assignment
PHP Array Operators
The PHP array operators are used to compare arrays.
Operator Name Example Result
+ Union $x + $y Union of $x and $y
== Equality $x == $y Returns true if $x and $y have the
same key/value pairs
=== Identity $x === $y Returns true if $x and $y have the
same key/value pairs in the same
order and of the same types
!= Inequality $x != $y Returns true if $x is not equal to $y
<> Inequality $x <> $y Returns true if $x is not equal to $y
!== Non-identity $x !== $y Returns true if $x is not identical to
$y
PHP Conditional Assignment Operators
The PHP conditional assignment operators are used to set a value depending on
conditions:
Operator Name Example Result
?: Ternary $x = expr1 ? expr2 : expr3 Returns the value of $x.
The value of $x is expr2 if expr1
= TRUE.
The value of $x is expr3 if expr1
= FALSE
PHP Conditional Statements

Very often when you write code, you want to perform different actions for different
conditions. You can use conditional statements in your code to do this.
In PHP we have the following conditional statements:
● if statement - executes some code if one condition is true
● if...else statement - executes some code if a condition is true and another code if that
condition is false
● if...elseif...else statement - executes different codes for more than two conditions
● switch statement - selects one of many blocks of code to be executed
PHP - The if Statement
The if statement executes some code if one condition is true.
Syntax
if (condition) {
code to be executed if condition is true;
}
Or
if (condition):
code to be executed if condition is true;
Endif;
Example
Output "Have a good day!" if the current time (HOUR) is less than 20:
<?php
$t = date("H");
if ($t < "20") {
echo "Have a good day!";
}
?>
Nested If statement
● Syntax:
If(condition)
{
Block of statement;
If(condition)
{
Block of statement;
}
If(condition)
{
Block of statement;
}
}
Or
● Syntax:
If(condition):
Block of statement;
If(condition):
Block of statement;
endif;

If(condition):
Block of statement;
endif;
endif;
PHP - The if...else Statement
The if...else statement executes some code if a condition is true and another code if that
condition is false.
Syntax
if (condition) {
code to be executed if condition is true;
} else {
code to be executed if condition is false;
}
Example :Output "Have a good day!" if the current time is less than 20, and "Have a good night!" otherwise:
<?php
$t = date("H");
if ($t < "20") {
echo "Have a good day!";
} else {
echo "Have a good night!";
}
?>
PHP - The if...elseif...else Statement
The if...elseif...else statement executes different codes for more than two conditions.
Syntax
if (condition) {
code to be executed if this condition is true;
} elseif (condition) {
code to be executed if first condition is false and this condition is true;
} else {
code to be executed if all conditions are false;
}
Example: Output "Have a good morning!" if the current time is less than 10, and "Have a
good day!" if the current time is less than 20. Otherwise it will output "Have a good
night!":
<?php
$t = date("H");

if ($t < "10") {


echo "Have a good morning!";
} elseif ($t < "20") {
echo "Have a good day!";
} else {
echo "Have a good night!";
}
?>
PHP switch Statement
Use the switch statement to select one of many blocks of code to be executed.
Syntax
switch (n) {
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
break;
case label3:
code to be executed if n=label3;
break;
...
default:
code to be executed if n is different from all labels;
}
Example
<?php
$favcolor = "red";

switch ($favcolor) {
case "red":
echo "Your favorite color is red!";
break;
case "blue":
echo "Your favorite color is blue!";
break;
case "green":
echo "Your favorite color is green!";
break;
default:
echo "Your favorite color is neither red, blue, nor green!";
}
?>
OR
Syntax
switch (n) :
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
break;
case label3:
code to be executed if n=label3;
break;
...
default:
code to be executed if n is different from all labels;
endswitch;
Break Statement
● This statement is used to stop loop or switch statement at any time.
● For eg:
<?php
for ($x = 1; $x <= 5; $x++)
{
If($x==2)
Break;
echo "The number is: $x <br/>";
}
?>
Continue Statement
● This statement is used to skip an iteration of loop.
● For eg:
<?php
for ($x = 1; $x <= 5; $x++)
{
If($x==2)
continue;
echo "The number is: $x <br/>";
}
?>
PHP Loops

Often when you write code, you want the same block of code to run over and over again a
certain number of times. So, instead of adding several almost equal code-lines in a script,
we can use loops.
Loops are used to execute the same block of code again and again, as long as a certain
condition is true.
In PHP, we have the following loop types:
● while - loops through a block of code as long as the specified condition is true
● do...while - loops through a block of code once, and then repeats the loop as long as
the specified condition is true
● for - loops through a block of code a specified number of times
● foreach - loops through a block of code for each element in an array
The PHP while Loop
The while loop executes a block of code as long as the specified condition is true.
Syntax
while (condition is true) {
code to be executed;
Increment / Decrement operator;
}
Examples
The example below displays the numbers from 1 to 5:
Example
<?php
$x = 1;
while($x <= 5) {
echo "The number is: $x <br>";
$x++;
}
?>
PHP do while Loop
The do...while loop will always execute the block of code once, it will then check the
condition, and repeat the loop while the specified condition is true.
Syntax
do {
code to be executed;
Increment / Decrement operator;
} while (condition is true);
Example:
<?php
$x = 1;
do {
echo "The number is: $x <br>";
$x++;
} while ($x <= 5);
?>
Note: In a do...while loop the condition is tested AFTER executing the statements within the loop. This means that the
do...while loop will execute its statements at least once, even if the condition is false. See example below.
The PHP for Loop
The for loop is used when you know in advance how many times the script should run.
Syntax
for (init counter; test counter; increment counter) {
code to be executed for each iteration;
}
Parameters:
● init counter: Initialize the loop counter value
● test counter: Evaluated for each loop iteration. If it evaluates to TRUE, the loop
continues. If it evaluates to FALSE, the loop ends.
● increment counter: Increases the loop counter value
Examples
The example below displays the numbers from 0 to 10:
Example
<?php
for ($x = 0; $x <= 10; $x++) {
echo "The number is: $x <br>";
}
?>
The PHP foreach Loop
The foreach loop works only on arrays, and is used to loop through each key/value pair in
an array.
Syntax
foreach ($array as $value) {
code to be executed;
}
For every loop iteration, the value of the current array element is assigned to $value and
the array pointer is moved by one, until it reaches the last array element.
Examples
The following example will output the values of the given array ($colors):
Example
<?php
$colors = array("red", "green", "blue", "yellow");

foreach ($colors as $value) {


echo "$value <br>";
}
?>
Single Quoted vs Double Quoted
● Single quote is said to be literal. It doesn’t parse the data
Double quote is said to be interpreted.
For ex:
<?php
$n=10;
echo "$n\n";
echo '$n';
?>
Output :
10
$n
● We can’t use single quote within single quote.
We can’t use double quote within double quote.
● We can use double quote within single quote.
We can use single quote within double quote.
Example :
<?php
echo "I am 'PHP'\n";
echo 'I am "PHP"';
?>
Output:
I am 'PHP'
I am "PHP"
● Use escape \ to use double quote within double quote.
Use escape \ to use single quote within single quote.
For Example:
<?php
echo "I am \"PHP\"\n";
echo 'I am \'PHP\'';
?>
Output:
I am "PHP"
I am 'PHP'
● \ and \\ only these two works with single quote.
All escape sequence works with double quotes.
Escape Sequence
● \n new line
● \r carriage return
● \t horizontal tab
● \v vertical tab
● \e escape
● \f form feed
● \\ backslash
● \$ dollar sign
● \” double quote
● \’ single quote
Example :
<?php
$MyString = "This is an \"escaped\" string";
$MySingleString = 'This \'will\' work';
$MyNonVariable = "I have \$zilch in my pocket";
$MyNewline = "This ends with a line return\n";
$MyFile = "c:\\windows\\system32\\myfile.txt";
echo "\n $MyString"; Output :
echo "\n $MySingleString"; This is an "escaped" string
echo "\n $MyNonVariable"; This 'will' work
echo "\n $MyNewline"; I have $zilch in my pocket
echo "\n $MyFile"; This ends with a line return
?>
c:\windows\system32\myfile.txt
$$
The $ operator in PHP is used to declare a variable. In PHP, a variable starts with
the $ sign followed by the name of the variable. For example, below is a string
variable:
$var_name = "Hello World!";

The $var_name is a normal variable used to store a value. It can store any value
like integer, float, char, string etc.
On the other hand, the $$var_name is known as reference variable where
$var_name is a normal variable. The $$var_name used to refer to the variable
with the name as value of the variable $var_name.
Example :
<?php
// Variable declaration and initialization
$var = "Hello";
$Hello = "GeeksforGeeks";

// Display the value of $var and $$var


echo $var . "\n";
echo $$var;
Output :
Hello
echo "\n\n";
GeeksforGeeks
?>
Dot(.) and Comma(,)
This is because PHP with dots joins the string first and then outputs them, while
with commas just prints them out one after the other.

For example:
<?php Output :
function dot() HelloWorld
{ echo "Hello" . "World\n"; } HelloWorld
function comma()
{ echo "Hello" , "World\n"; }
dot();
comma();
?>

You might also like