Unit-II PHP
Unit-II PHP
o All variables in PHP are denoted with a leading dollar sign ($).
o Variables are assigned with the = operator, with the variable on the left-hand
side and the expression to be evaluated on the right.
o Variables in PHP do not have intrinsic types - a variable does not know in
advance whether it will be used to store a number or a string of characters.
o PHP does a good job of automatically converting types from one to another
when necessary.
o PHP variables are Perl-like.
Variable Naming
A variable name can consist of numbers, letters, underscores but you cannot use
characters like + , - , % , ( , ) . & , etc
Data Types
PHP has a total of eight data types which we use to construct our variables −
Resources − are special variables that hold references to resources external to PHP
(such as database connections).
The first five are simple types, and the next two (arrays and objects) are compound - the
compound types can package up other arbitrary values of arbitrary type, whereas the simple
types cannot.
Integers
Integers hold only whole numbers including positive and negative numbers, i.e.,
numbers without fractional part or decimal point. They can be decimal (base 10),
octal (base 8), or hexadecimal (base 16). The default base is decimal (base 10).
The octal integers can be declared with leading 0 and the hexadecimal can be
declared with leading 0x. The range of integers must lie between -2^31 to 2^31.
Example program:
<?php
Doubles
A floating-point number is a number with a decimal point. Unlike integer, it can hold numbers with a
fractional or decimal point, including a negative or positive sign.
Example Program:
<?php
$val1 = 50.85;
$val2 = 654.26;
$sum = $val1 + $val2;
echo $sum;
echo "\n\n";
//returns data type and value
var_dump($sum)
?>
705.11
float(705.11)
Boolean
Boolean data types are used in conditional testing. Hold only two values, either
TRUE(1) or FALSE(0). Successful events will return true and unsuccessful
events return false. NULL type values are also treated as false in Boolean. Apart
from NULL, 0 is also considered false in boolean. If a string is empty then it is
also considered false in boolean data type.
<?php
if(TRUE)
echo "This condition is TRUE";
if(FALSE)
echo "This condition is not TRUE";
?>
Here are the rules for determine the "truth" of any value not already of the Boolean type −
If the value is a number, it is false if exactly equal to zero and true otherwise.
<?php
// Declare a number
$number = 0; // Change this value to test with different numbers
If the value is a string, it is false if the string is empty (has zero characters) or is the string
"0", and is true otherwise.
<?php
// Declare a string
$string = "0"; // Change this value to test different strings
Output:
If the value is an array, it is false if it contains no other values, and it is true otherwise.
For an object, containing a value means having a member variable that has been assigned
a value.
<?php
// Example with an array
$array = []; // Change this to test with non-empty arrays
Output:
$array = []; $object->value = null;
The array is considered FALSE in PHP.
The object is considered FALSE because it has no member variable with a value.
Input: $array = [1, 2, 3]; $object->value = "Hello";
The array is considered TRUE in PHP.
The object is considered TRUE because it has a member variable with a value.
Valid resources are true (although some functions that return resources when they are
successful will return FALSE when unsuccessful).
<?php
// Attempt to open a file
$file = fopen("example.txt", "r"); // "r" mode is for reading
Each of the following variables has the truth value embedded in its name when it is used in a
Boolean context.
$true_num = 3 + 0.14159;
$true_str = "Tried and true"
$true_array[49] = "An array element";
$false_array = array();
$false_null = NULL;
$false_num = 999 - 999;
$false_str = "";
NULL
NULL is a special type that only has one value: NULL. To give a variable the NULL value,
simply assign it like this −
$my_var = NULL;
The special constant NULL is capitalized by convention, but actually it is case insensitive;
you could just as well have typed −
$my_var = null;
A variable that has been assigned NULL has the following properties −
Strings
A string is a non-numeric data type. It holds letters or any alphabets, numbers, and even special
characters.
String values must be enclosed either within single quotes or in double quotes. But both are treated
differently. To clarify this, see the example below:
They are sequences of characters, like "PHP supports string operations". Following are valid
examples of string
Singly quoted strings are treated almost literally, whereas doubly quoted strings replace
variables with their values as well as specially interpreting certain character sequences.
<?php
// Variable declaration
$name = "Alice";
$age = 25;
$single_quoted = 'My name is $name and I am $age years old.\nThis is a new line.';
$double_quoted = "My name is $name and I am $age years old.\nThis is a new line.";
echo "Single-quoted string:<br>";
echo $single_quoted;
echo "<br><br>";
echo "Double-quoted string:<br>";
echo $double_quoted;
?>
Single-Quoted Strings:
Treated literally.
Variables are not expanded.
Escape sequences like \n and \t are not interpreted, except for \\ (a literal backslash)
and \' (a single quote).
Double-Quoted Strings:
Strings that are delimited by double quotes (as in "this") are preprocessed in both the
following two ways by PHP −
Certain character sequences beginning with backslash (\) are replaced with special
characters
Variable names (starting with $) are replaced with string representations of their values.
Variable Scope
Scope can be defined as the range of availability a variable has to the program in which it is
declared. PHP variables can be one of four scope types −
Local variables
The variables declared within a function are called local variables to that function
and have their scope only in that particular function.
<?php
$num = 60;
function local_var()
{
// This $num is local to this function
// the variable $num outside this function
// is a completely different variable
$num = 50;
echo "local num = $num \n";
}
local_var();
?>
Output
local num = 50
Variable num outside local_var() is 60
Global variables
The variables declared outside a function are called global variables. These variables can be
accessed directly outside a function. To get access within a function we need to use the
“global” keyword before the variable to refer to the global variable.
<?php
$num = 20;
global_var();
echo "Variable num outside function : $num \n";
?>
Output:
Static variables
It is the characteristic of PHP to delete the variable, once it completes its execution and the
memory is freed. But sometimes we need to store the variables even after the completion of
function execution. To do this we use the static keywords and the variables are then called
static variables. PHP associates a data type depending on the value for the variable.
Example Program:
function counterExample() {
static $count = 0; // Retains value between function calls
$count++;
echo "Static Count: $count\n";
}
Operators
Operator is a symbol used to perform operations on operands. In simple words,
operators are used to perform operations on variables or values. For example:
$num=10+20;//+ is the operator and 10,20 are operands.
PHP language supports following type of operators.
Arithmetic Operators
Comparison Operators
Logical (or Relational) Operators
Assignment Operators
Conditional (or ternary) Operators
Arithmetic Operators
A + B will give
+ Adds two operands
30
A - B will give -
- Subtracts second operand from the first
10
A * B will give
* Multiply both operands
200
Comparison Operators
Operato
Description Example
r
Logical Operators
Operato
Description Example
r
Assignment Operators
Operato
Description Example
r
C = A + B will
Simple assignment operator, Assigns values
= assign value of A +
from right side operands to left side operand
B into C
Conditional Operator
There is one more operator called conditional operator. This first evaluates an expression for
a true or false value and then execute one of the two given statements depending upon the
result of the evaluation. The conditional operator has this syntax −
Show Examples
Operato
Description Example
r
Operators Categories
All the operators we have discussed above can be categorised into following categories −
o Binary operators, which take two operands and perform a variety of arithmetic
and logical operations.
o The conditional operator (a ternary operator), which takes three operands and
evaluates either the second or third expression, depending on the evaluation of
the first expression.
o Assignment operators, which assign a value to a variable.
Operator precedence determines the grouping of terms in an expression. This affects how an
expression is evaluated. Certain operators have higher precedence than others; for example,
the multiplication operator has higher precedence than the addition operator −
For example x = 7 + 3 * 2; Here x is assigned 13, not 20 because operator * has higher
precedence than + so it first get multiplied with 3*2 and then adds into 7.
Here operators with the highest precedence appear at the top of the table, those with the
lowest appear at the bottom. Within an expression, higher precedence operators will be
evaluated first.
<?php
// function to demonstrate static variables
function static_var()
{
// static variable
static $num = 5;
$sum = 2;
$sum++;
$num++;
echo $num, "\n";
echo $sum, "\n";
}
?>
Output:
6
3
7
3
Conditional Statements
The if, elseif ...else and switch statements are used to take decision based on the different
condition.
if...else statement − use this statement if you want to execute a set of code when a
condition is true and another if the condition is not true
elseif statement − is used with the if...else statement to execute a set of code if one of
the several condition is true
switch statement − is used if you want to select one of many blocks of code to be
executed, use the Switch statement. The switch statement is used to avoid long blocks
of if..elseif..else code.
If you want to execute some code if a condition is true and another code if a condition is
false, use the if....else statement.
Syntax
if (condition)
code to be executed if condition is true;
else
code to be executed if condition is false;
Example
The following example will output "Have a nice weekend!" if the current day is Friday,
Otherwise, it will output "Have a nice day!":
<html>
<body>
<?php
$d = date("D");
if ($d == "Fri")
echo "Have a nice weekend!";
else
echo "Have a nice day!";
?>
</body></html>
Syntax
if (condition)
code to be executed if condition is true;
elseif (condition)
code to be executed if condition is true;
else
code to be executed if condition is false;
Example
The following example will output "Have a nice weekend!" if the current day is Friday, and
"Have a nice Sunday!" if the current day is Sunday. Otherwise, it will output "Have a nice
day!" −
<html>
<body>
<?php
$d = date("D");
if ($d == "Fri")
echo "Have a nice weekend!";
else
echo "Have a nice day!";
?>
</body></html>
If you want to select one of many blocks of code to be executed, use the Switch statement.
Syntax
switch (expression){
case label1:
code to be executed if expression = label1;
break;
case label2:
code to be executed if expression = label2;
break;
default:
code to be executed
if expression is different
from both label1 and label2;
}
Example
The switch statement works in an unusual way. First it evaluates given expression then seeks
a lable to match the resulting value. If a matching value is found then the code associated
with the matching label will be executed or if none of the lable matches then statement will
execute any specified default code.
<html>
<body>
<?php
$d = date("D");
switch ($d){
case "Mon":
echo "Today is Monday";
break;
case "Tue":
echo "Today is Tuesday";
break;
case "Wed":
echo "Today is Wednesday";
break;
case "Thu":
echo "Today is Thursday";
break;
case "Fri":
echo "Today is Friday";
break;
case "Sat":
echo "Today is Saturday";
break;
case "Sun":
echo "Today is Sunday";
break;
default:
echo "Wonder which day is this ?";
}
?>
</body></html>
Today is Monday
Loops in PHP are used to execute the same block of code a specified number of times. PHP
supports following four loop types.
for − loops through a block of code a specified number of times.
while − loops through a block of code if and as long as a specified condition is true.
do...while − loops through a block of code once, and then repeats the loop as long as a
special condition is true.
foreach − loops through a block of code for each element in an array.
The for statement is used when you know how many times you want to execute a statement
or a block of statements.
Syntax
The initializer is used to set the start value for the counter of the number of loop iterations. A
variable may be declared here for this purpose and it is traditional to name it $i.
Example
The following example makes five iterations and changes the assigned value of two variables
on each pass of the loop −
<html>
<body>
<?php
$a = 0;
$b = 0;
The while statement will execute a block of code if and as long as a test expression is true.
If the test expression is true then the code block will be executed. After the code has executed
the test expression will again be evaluated and the loop will continue until the test expression
is found to be false.
Syntax
while (condition) {
code to be executed;
}
Example
This example decrements a variable value on each iteration of the loop and the counter
increments until it reaches 10 when the evaluation is false and the loop ends.
<html>
<body>
<?php
$i = 0;
$num = 50;
</body></html>
The do...while statement will execute a block of code at least once - it then will repeat the
loop as long as a condition is true.
Syntax
do {
code to be executed;
}
while (condition);
Example
The following example will increment the value of i at least once, and it will continue
incrementing the variable i as long as it has a value of less than 10 −
<html>
<body>
<?php
$i = 0;
$num = 0;
do {
$i++;
}
while( $i < 10 );
echo ("Loop stopped at i = $i" );
?>
</body></html>
Loop stopped at i = 10
The foreach statement is used to loop through arrays. For each pass the value of the current
array element is assigned to $value and the array pointer is moved by one and in the next pass
next element will be processed.
Syntax
Example
<html>
<body>
<?php
$array = array( 1, 2, 3, 4, 5);
</body></html>
Value is 1
Value is 2
Value is 3
Value is 4
Value is 5