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

Unit-II PHP

This document provides an introduction to PHP variables, data types, and operators. It covers the rules for variable naming, the eight data types in PHP, and the differences between single-quoted and double-quoted strings. Additionally, it explains variable scope, including local, global, and static variables, as well as various operators used in PHP.

Uploaded by

Durga Nadarajan
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)
2 views

Unit-II PHP

This document provides an introduction to PHP variables, data types, and operators. It covers the rules for variable naming, the eight data types in PHP, and the differences between single-quoted and double-quoted strings. Additionally, it explains variable scope, including local, global, and static variables, as well as various operators used in PHP.

Uploaded by

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

Unit-II

Introduction to PHP Variable -Understanding Data Types -Using Operators -Using


Conditional Statements -If (),else if () and else if condition Statement -Switch () Statements -
Using the while () Loop -Using the for() Loop
PHP Variables
Variables in a program are used to store some values or data that can be used later in a
program. The variables are also like containers that store character values, numeric values,
memory addresses, and strings.
There are a few rules, that need to be followed and facts that need to be kept in mind while
dealing with variables in PHP:

o All variables in PHP are denoted with a leading dollar sign ($).

o The value of a variable is the value of its most recent assignment.

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 can, but do not need, to be declared before assignment.

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 Variables used before they are assigned have default values.

o PHP does a good job of automatically converting types from one to another
when necessary.
o PHP variables are Perl-like.

Variable Naming

Rules for naming a variable is −

 Variable names must begin with a letter or underscore character.

 A variable name can consist of numbers, letters, underscores but you cannot use
characters like + , - , % , ( , ) . & , etc

 There is no size limit for variables.

Data Types

PHP has a total of eight data types which we use to construct our variables −

Integers − are whole numbers, without a decimal point, like 4195.


Doubles − are floating-point numbers, like 3.14159 or 49.1.

Booleans − have only two possible values either true or false.

NULL − is a special type that only has one value: NULL.

Strings − are sequences of characters, like 'PHP supports string operations.'

Arrays − are named and indexed collections of other values.

Objects − are instances of programmer-defined classes, which can package up both


other kinds of values and functions that are specific to the class.

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

// decimal base integers


$deci1 = 50;
$deci2 = 654;

// octal base integers


$octal1 = 07;

// hexadecimal base integers


$octal = 0x45;

$sum = $deci1 + $deci2;


echo $sum;
echo "\n\n";

//returns data type and value


var_dump($sum)
?>
Output:
704
int(704)

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

It produces the following browser output −

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

Interpreting other types as Booleans

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

// Check the boolean equivalent of the number


if ($number) {
echo "The number $number is considered TRUE in PHP.";
} else {
echo "The number $number is considered FALSE in PHP.";
}
?>

If the input $number = 0


The number 0 is considered FALSE in PHP.
If the input $number = 10
The number 10 is considered TRUE in PHP.

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

// Check the boolean equivalent of the string


if ($string) {
echo "The string \"$string\" is considered TRUE in PHP.";
} else {
echo "The string \"$string\" is considered FALSE in PHP.";
}
?>

Output:

The string "" is considered FALSE in PHP.


The string "0" is considered FALSE in PHP.
The string "hello" is considered TRUE in PHP.
The string "123" is considered TRUE in PHP.

 Values of type NULL are always false.

 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

// Check the boolean equivalent of the array


if ($array) {
echo "The array is considered TRUE in PHP.<br>";
} else {
echo "The array is considered FALSE in PHP.<br>";
}

// Example with an object


class TestObject {
public $value; // Member variable
}

$object = new TestObject(); // Create an object


$object->value = null; // Change to a value to test different cases

// Check if the object is considered true


if (!empty((array) $object)) {
echo "The object is considered TRUE because it has a member variable with a value.";
} else {
echo "The object is considered FALSE because it has no member variable with a
value.";
}
?>

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

// Check if the file resource is valid


if ($file) {
echo "The file resource is valid. The file is open for reading.<br>";

// Close the resource


fclose($file);
} else {
echo "Failed to open the file. The file resource is invalid.<br>";
}
?>

Don't use double as Booleans.

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 −

 It evaluates to FALSE in a Boolean context.

 It returns FALSE when tested with IsSet() function.

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

$string_1 = "This is a string in double quotes";


$string_2 = 'This is a somewhat longer, singly quoted string';
$string_39 = "This string has thirty-nine characters";
$string_0 = ""; // a string with zero characters

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

This will produce following result −


Single-quoted string:
My name is $name and I am $age years old.\nThis is a new line.
Double-quoted string:
My name is Alice and I am 25 years old.
This is a new line.

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:

 Allow variable interpolation (variables are replaced with their values).


 Special character sequences such as \n (newline), \t (tab), and others are interpreted.
There are no artificial limits on string length - within the bounds of available memory, you
ought to be able to make arbitrarily long 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.

The escape-sequence replacements are −

 \n is replaced by the newline character


<?php
$text = "Line 1\nLine 2";
echo $text;
?>
 \r is replaced by the carriage-return character
$text = "Hello\rWorld";
echo $text;

 \t is replaced by the tab character


$text = "Name:\tJohn";
echo $text;

 \$ is replaced by the dollar sign itself ($)


$text = "The price is \$10";
echo $text;
 \" is replaced by a single double-quote (")
$text = "She said, \"Hello!\"";
echo $text;

 \\ is replaced by a single backslash (\)


$text = "This is a backslash: \\";
echo $text;

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

// $num outside function local_var() is a


// completely different Variable than that of
// inside local_var()
echo "Variable num outside local_var() is $num \n";

?>

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;

// function to demonstrate use of global variable


function global_var()
{
// we have to use global keyword before
// the variable $num to access within
// the function
global $num;

echo "Variable num inside function : $num \n";


}

global_var();
echo "Variable num outside function : $num \n";

?>

Output:

Variable num inside function : 20


Variable num outside function : 20

 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";
}

counterExample(); // Output: Static Count: 1


counterExample(); // Output: Static Count: 2
counterExample(); // Output: Static Count: 3

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

There are following arithmetic operators supported by PHP language −

Assume variable A holds 10 and variable B holds 20 then −


Operato
Description Example
r

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

/ Divide numerator by de-numerator B / A will give 2

Modulus Operator and remainder of after an B % A will give


%
integer division 0

Increment operator, increases integer value by A++ will give


++
one 11

Decrement operator, decreases integer value by


-- A-- will give 9
one

Comparison Operators

There are following comparison operators supported by PHP language

Assume variable A holds 10 and variable B holds 20 then −

Operato
Description Example
r

Checks if the value of two operands are equal or (A == B) is


==
not, if yes then condition becomes true. not true.

Checks if the value of two operands are equal or


(A != B) is
!= not, if values are not equal then condition becomes
true.
true.

Checks if the value of left operand is greater than


(A > B) is
> the value of right operand, if yes then condition
not true.
becomes true.

Checks if the value of left operand is less than the


(A < B) is
< value of right operand, if yes then condition
true.
becomes true.

>= Checks if the value of left operand is greater than (A >= B) is


or equal to the value of right operand, if yes then
not true.
condition becomes true.

Checks if the value of left operand is less than or


(A <= B) is
<= equal to the value of right operand, if yes then
true.
condition becomes true.

Logical Operators

There are following logical operators supported by PHP language

Assume variable A holds 10 and variable B holds 20 then −

Operato
Description Example
r

Called Logical AND operator. If both the operands (A and B) is


And
are true then condition becomes true. true.

Called Logical OR Operator. If any of the two (A or B) is


Or
operands are non zero then condition becomes true. true.

Called Logical AND operator. If both the operands (A && B)


&&
are non zero then condition becomes true. is true.

Called Logical OR Operator. If any of the two (A || B) is


||
operands are non zero then condition becomes true. true.

Called Logical NOT Operator. Use to reverses the


!(A && B)
! logical state of its operand. If a condition is true
is false.
then Logical NOT operator will make false.

Assignment Operators

There are following assignment operators supported by PHP language −

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

+= Add AND assignment operator, It adds right C += A is


operand to the left operand and assign the
result to left operand
$x = 5; equivalent to C = C
$y = 3; +A
$x += $y; // Equivalent to $x = $x + $y;
echo $x; // Output: 8

Subtract AND assignment operator, It


C -= A is equivalent
-= subtracts right operand from the left
to C = C - A
operand and assign the result to left operand

Multiply AND assignment operator, It C *= A is


*= multiplies right operand with the left equivalent to C = C
operand and assign the result to left operand * A

Divide AND assignment operator, It divides


C /= A is equivalent
/= left operand with the right operand and
to C = C / A
assign the result to left operand

Modulus AND assignment operator, It takes C %= A is


%= modulus using two operands and assign the equivalent to C = C
result to left operand %A

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

Conditional If Condition is true ? Then value X :


?:
Expression Otherwise value Y

Operators Categories

All the operators we have discussed above can be categorised into following categories −

o Unary prefix operators, which precede a single operand.

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.

Precedence of PHP Operators

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.

Category Operator Associativity

Unary ! ++ -- Right to left

Multiplicative */% Left to right

Additive +- Left to right

Relational < <= > >= Left to right

Equality == != Left to right

Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left

Assignment = += -= *= /= %= Right to left

<?php
// function to demonstrate static variables
function static_var()
{
// static variable
static $num = 5;
$sum = 2;

$sum++;
$num++;
echo $num, "\n";
echo $sum, "\n";
}

// first function call


static_var();

// second function call


static_var();

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

The If...Else Statement

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>

It will produce the following result −

Have a nice weekend!

The ElseIf Statement


If you want to execute some code if one of the several conditions are true use the elseif
statement

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

elseif ($d == "Sun")


echo "Have a nice Sunday!";

else
echo "Have a nice day!";
?>

</body></html>

It will produce the following result −

Have a nice Weekend!

The Switch Statement

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.

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>

It will produce the following result −

Today is Monday

PHP - Loop Types

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 loop statement

The for statement is used when you know how many times you want to execute a statement
or a block of statements.
Syntax

for (initialization; condition; increment){


code to be executed;
}

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;

for( $i = 0; $i<5; $i++ ) {


$a += 10;
$b += 5;
}

echo ("At the end of the loop a = $a and b = $b" );


?>
</body></html>

This will produce the following result −

At the end of the loop a = 50 and b = 25

The while loop statement

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;

while( $i < 10) {


$num--;
$i++;
}

echo ("Loop stopped at i = $i and num = $num" );


?>

</body></html>

This will produce the following result −

Loop stopped at i = 10 and num = 40

The do...while loop statement

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>

This will produce the following result −

Loop stopped at i = 10

The foreach loop statement

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

foreach (array as value) {


code to be executed;
}

Example

Try out following example to list out the values of an array.

<html>
<body>

<?php
$array = array( 1, 2, 3, 4, 5);

foreach( $array as $value ) {


echo "Value is $value <br />";
}
?>

</body></html>

This will produce the following result −

Value is 1
Value is 2
Value is 3
Value is 4
Value is 5

You might also like