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

PHP_Ch_1

Uploaded by

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

PHP_Ch_1

Uploaded by

Samiksha Bhosale
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 52

Ch-1 Expressions and Control Statements in PHP Marks -12

Define PHP

PHP stands for Hypertext Preprocessor. PHP is widely-used open source


server-side scripting language to write dynamically generated web pages. PHP
scripts are executed on the server and the result is sent to the browser as plain
HTML.

PHP can be integrated with the number of popular databases, including MySQL,
PostgreSQL, Oracle, Sybase, Informix, and Microsoft SQL Server.
Why PHP is known as scripting language?

Scripting language : A scripting language or script language is a programming


language that supports scripts. If code of programming language can embed
with other language or integrate with other language or script called scripting
language. PHP is Scripting language because we can embed PHP code into
HTML. PHP is server side language because PHP requires server to run a code.
Code of PHP gets executed on server and result of execution is return to the
browser, that's why PHP is called script language and server side language.

Open Source : PHP is open source and free of cost, which helps developers to
install it quickly and readily available for use.

1.Platform independent
2.Simple & easy
3.Databse
4.Fast
5.Security
Syntax of PHP

What these tags specify in PHP <?php and ?>?

A PHP script starts with the <?php and ends with the ?> tag.

The PHP delimiter <?php and ?> in the example simply tells the PHP engine to
treat the enclosed code block as PHP code, rather than simple HTML.

On servers with shorthand support enabled, you can start a scripting block with
<? and end with ?>.
Example:
Syntax :
<html>
<?php
<body>
echo 'Hello world!’;
<?php echo "Hello World“;
?>
?>

</body>

</html>
Embedding PHP within HTML

PHP files are plain text files with .php extension. Inside a PHP file you can write
HTML like you do in regular HTML pages as well as embed PHP codes for server side
execution.

<!DOCTYPE html>

<html lang="en">

<head>
<meta charset="UTF-8">
<title> Simple PHP File</title>
</head>

<body>
<hl><?php echo "Hello, world!"; ?></h1>
</body>

</html>
PHP Comments

Example :

<?php

// This is a single line comment

# This is also a single line comment

/* This is also a multiline comment


For more than one line */

echo “Hello World!”;

?>
The PHP echo Statement

The echo statement can be used with or without parentheses: echo or echo().

The echo statement can display anything that can be displayed to the browser, such
as string, numbers, variables values, the results of expressions etc.

Example:

<?php

// Displaying strings
echo "Hello, Welcome to PHP Programming";
echo "<br/>";
/Displaying Strings as Multiple arguments
echo "Hello", " Welcome", " PHP";
echo "<br/>";
//Displaying variables
Output :
$s="Hello, PHP";
Hello, Welcome to PHP Programming
$x=10;
Hello Welcome PHP
$y=20;
Hello, PHP
echo “$s <br/>"}
10+20=30
echo $x."+"$y."=";
echo $x + $y;
The PHP print Statement

Example:

php
Expressions and Control Statements in PHE
// Displaying strings
print "Hello, Welcome to PHP Programming“;
print "<br/>";

/Displaying variables

$s="Hello, PHP";
$x=10;
$y=20;
print “$s <br/>";
print $x."+".$y."=";
print $x + $y;

Output:
Hello, Welcome to PHP Programming
Hello, PHP
10+20=30
Variables in PHP -

Variables are used to store data, like string of text, numbers, etc. Variable values can
change over the course of a script.

In PHP, a variable does not need to be declared before adding a value to it. PHP
automatically converts the variable to the correct data type, depending on its value.

After declaring a variable it can be reused throughout the code.

In PHP, a variable starts with the $ sign, followed by the name of the variable:

The assignment operator (=) used to assign value to a variable.

In PHP variable can be declared as : $var name = value;

eg.- $name = “Omkar”;


1.Rules for Variables -

1) Variable must start with '$'


2) Variable name must start with a letter or underscore charactere.
3) Variable name can not start with a number.
4) Variable name can only contain alpha numeric and (-) underscore.
5) Variable names are case-Sensitive.

Declaring a Variable

1) We can declare a variable in PHP by using


2) e.g. - $x;
$name;

2.Initiating a variable -
We can assign a value to a variable by using assignment operator (=)
e.g. $x = 2;
$name = "neha";

3.Displaying Variable -
A In PHP, echo statement is used to display “String “ or value of variable.
2) We have to pass n without enclosing it in question mark.

eg. $age= 18;


echo $age

3) To display both text strings and variables send them to the echo statement as
individual arguments separated by commas ( , )

echo "<p> The age is ", $age," </P>.";


Scope of a variable –

Scope of a variable is defined as its extent in program within which it can be


accessed, i.e. the scope of a variable is the portion of the program with in which it is
visible or can be accessed. There are three different variable scope:

1. Local Variables

The variables declared within a function are called local variables to that function
and has its scope only in that particular function. Local variables cannot be accessed
outside that function. Any declaration of a variable outside the function with same
name as that of the one within the function is a complete different variable.
Output: local num = 10
Variable num outside local var() = 20
2.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.

Example:

Output:Access global variable within function=20


Global variable num outside of local var()-20
Static Variables -

It is the characteristic of PHP to delete the


variable, ones 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 static keyword and the
variables are then called as static variables.
PHP $ and $$ Variables -

State the difference between $ and $$ in PHP.

The $var (single dollar) is a normal variable with the name var that stores any
value like string, integer, float, etc. Example : $x="Hello";

The $$var (double dollar) is a reference variable that stores the value of the
$variable inside it (variable of a variable). Example : $$x=100

$x represents variables whereas $$x represents a variable with the content of $x

$$x = $($x) = $("Hello") = $Hello = PHP

Data stored in $ is fixed while data stored in $$(double dollar sign) can be changed
dynamically.
Example:

<?php

$x="Hello";

$$x="PHP";

echo $x."<br/>";

echo $$x."<br/>";

echo $Hello;

?>

Output:

Hello

PHP

PHP
Datatypes -
Integer - An Integer is whole numbers. ( without decimals)
eg.
$a =1234;

Float - A Float ( Floating point number) is a number with decimal point .

eg- $ b = 12.02;

Boolean - Boolean represents two possible states true or false. Booleans are often
used in conditional testing.
eg.
$x = true;
$y = false;
Pre-defined variables -
PHP pre-defined variables are also known as super global variables which means
that they are always accessible regardless of their scope.

eg.

$GLOBALS $_POST
$_SERVER $_ENV
$- REQEST $_COOKIE
$_GET $_SESSION

Constants -

1)Constants are special variables that cannot be changed.


2) Constants, names do not begin with a '$ dollar sign.
3) Use them for named items that will not change.
4) Constant names are use all uppercase letters.
5) Use the define () function to create a constant -define (-CONSTANL NAME"
value);
6) The value you pass to the define to the define () function be a text String
number or Boolean value.
Expressions and Operators
1.Arithmatic Operators
2. Assignment Operators
3. Comparison Operators
4. Increment/Decrement Operators
5. Logical or Relational Operators
6. String Operators
7. Array Operators
8. Conditional or Ternary Operators
9. Spaceship Operators (Introduced in PHP 7)
10. Bitwise Operators
Arithmetic Operators
Arithmetic operators are used in mathematical expression in the same way like
addition, subtraction, multiplication etc, that they are used in algebra.
Assignment Operators –
Assignment operators are used to assign the value of an expression to a variable.
Increment/Decrement Operators –

Increment operators are called the unary operators as it work on single operands .

The operator ++ adds one to the operand and -- subtract one from the operand.
Logical or Relational Operators

Logical operators are basically used to operate with conditional statements and
expressions. Conditional statements are based on conditions. Conditional statement
can either be true or false.
String Operators
There are two string operators. The first is the concatenation operator ("), which
returns the concatenation of Two strings Le join right and left arguments. The
second is the concatenating assignment operator ('.='), which appends the
argument on the right side to the argument on the left side.
Array Operators

We can perform operations on arrays using Arrays Operators like Union, Equality,
Identity, Inequality and Non-identity.

Assume $a and $b are arrays.


Spaceship Operators (Introduced in PHP 7)

PHP 7 has introduced a new kind of operator called spaceship operator (). These
operators are used to compare values but instead of returning Boolean result, it
returns integer values. It returns -1, 0 or 1. If both the operands are equal, it
returns 0. If the right operand is greater, it returns -1. If the left operand is greater,
it returns 1.
Bitwise Operators –
The Bitwise operators is used to perform bit-level operations on the operands.
Constants-
A constant is a name or an identifier for a fixed value.

A constant value cannot change during the execution of the script.

By convention, constant identifiers are always uppercase.

By default, a constant is case-sensitive.

A constant name starts with a letter or underscore, followed by any number of


letters, numbers, or underscores.

If you have defined a constant, it can never be changed or undefined.

Common examples of such data include configuration settings such as database


username and password, website's base URL, company name, etc.

The define() function in PHP is used to create a constant


Syntax : define(name, value, case-insensitive)

Where,

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.
Decision Making Control Statements
if statement -

The if statement is used to execute a block of code only if the specified condition
evaluates to true.
Syntax :

if(condition)
{
// Code to be executed
}

Example:

<?php
$a=10;
if ($a > 0)
{
echo "The number is positive";
}
?>

Output:
The number is positive
if-else Statement -

If...else statement first checks the condition. If condition is true, then true
statement block is executed. If condition is false, then false statement block is
executed.

Syntax:

if (condition)
{

// if TRUE then execute this code


}
else
{

// if FALSE then execute this code


}
Example :

<?php

$a=-10;

if ($a> 0)
{
echo "The number is positive";

else

echo "The number is negative",


}
?>

Output:

The number is negative.


Nested-if Statement

Nested if statements mean an if block inside another if block. Nested if else


statement used when we have more than two conditions. It is also called if else if
statement.

Syntax :

if(condition1)
{
// Code to be executed if condition is true
}

elseif(condition2)
{
code to be executed if the condition 1 is false and condition 2 is true
}

else
{
// Code to be executed if both condition and condition2 are false
}
Example :
<?php
$per=65;
if ($per >=75)
{
echo "Distinction";
}
else if ($per <75 && $per >=60)
{
echo "First Class";
}

else if ($per <60 && $per >= 45)


{
echo "Second Class";
}
else if ($per <45 && $per >= 40)
{
echo "Pass Class";
}
else
Output:
{
echo " Fail";
First Class
}
Switch Statement
The switch-case statement is
an alternative to the if-elseif-
else statement, which does
almost the same thing. The
switch-case statement tests a
variable against a series of
values until it finds a match,
and then executes the block of
code corresponding to that
match. The switch statement
is used to avoid long blocks of
if..elseif..else code.
Syntax:

switch(n)

case statement1:
//code to be executed if n ==statement1;

break;

case statement2:

//code to be executed if n ==statement2;

break;

case statement3:

//code to be executed if n== statement3;

break; break;

case statement4: default:

//code to be executed if n ==statement4; //code to be executed if n !=any case;


}
Example: echo "Subtraction=".$c

<?php break;

$ch=1; case 3:

$a=20; $c=$a*$b;

$b=10; echo "Multiplication=". $c;

switch ($ch) break;

case 1: case 4:

$c=$a+$b; $c=$a/$b;

echo "Addition=".$c; echo "Division=".$c;

break; break;

case 2: default:

$c=$a - $b; echo "Wrong Choice":


Output: Addition 30
Break and Continue Statement –
There are two special statements that can be used inside loops: Break and Continue

Break The keyword break ends execution of the current for, for each, while, do while or switch
structure. When the keyword break executed inside a loop the control automatically passes to
the first statement outside the loop. A break is usually associated with the if.

Example:

Output –
1
2
3
2.Continue :

It is used to stop processing the current block of code in the loop and goes to the
next iteration. It is used to skip a part of the body of the loop under certain
conditions. It causes the loop to be continued with the next iteration after skipping
any statement in between.

The continue statement tells the compiler


"SKIP THE FOLLOWING STATEMENTS AND CONTINUE WITH THE NEXT ITERATION".

<?php

for($i=1; $i<=5;$i++)
{ Output:
if($i ==3) 1
{ 2
continue; 4
} 5
echo "$i<br/>“;
}

?>
Loop Control Statements –

while Statement

The while statement will execute a block of code if and as long as a test condition is
true. The while is an entry controlled loop statement. i.e., it first checks the
condition at the start of the loop and if its true then it enters the loop and executes
the block of statements, and goes on executing it as long as the condition holds
true.

Syntax :
while (if the condition is true)
{

// code is executed

}
Example:

<?php

//while loop to print even numbers

$i=0;

while ($i<= 10)


{
echo "$i<br/>"; Output:
$i+=2;
} 0

?> 2

10
do-while Statement -
This is an exit control loop which means that it first enters the loop, executes the
statements, and then checks the condition. Therefore, a statement is executed at
least once on using the do...while loop. After executing once, the program is
executed as long as the condition holds true.

Syntax:

do
{

//code is executed

} while (if condition is true);


Example :

<?php

//do-while loop to print odd numbers

$i=1;

do

{
echo "$i<br/>";
$i+=2; Output: 1
3
}while ($i< 10); 5
7
?> 9
for Statement
The for statement is used when you know how many times you want to execute a
statement or a block of statements. That is, the number of iterations is known
beforehand.

If statement is true, then loop body is executed and loop variable gets updated.
Steps are repeated till exit condition comes.

Initialization Expression: In this expression we have to initialize the loop counter to


some value. for example: $i=1;

Test Expression: In this expression we have to test the condition. If the condition
evaluates to true then we will execute the body of loop and go to update expression
otherwise we will exit from the for loop. For example: $i<=10;

3. Update Expression: After executing loop body this expression


increments/decrements the loop variable by some value. for example: $i+= 2;
Syntax:

for (initialization expression; test condition; update expression)

{
// code to be executed
}
Example:

<?php

for loop to print even numbers and sum of them

$sum=0;

for($i=0; $i<=10; $i+=2) Output:


{
echo "$i<br/>"; 0

$sum+=Si; 2

} 4

echo "Sum-=$sum"; 6
?>
8

10

Sum=30
foreach Statement

foreach loop is used for array and objects. For every counter of loop, an array
element is assigned and the next counter is shifted to the next element.

Syntax:

foreach (array_element as value)

{
//code to be executed
}
Example: Output:

<?php 10

$arr=array (10, 20, 30, 40, 50); 20


foreach ($arr as $i )
{ 30
echo "$i<br/>";
} 40

?> 50
Write a program in PHP to calculate Square
Root of a number.

<? Php
Programs
function my_sqrt($n)
{

$x = $n;
$y = 1;

while($x> Sy)
{

$x=($x + $y)/2;
$y = $n/Sx;

}
return $x;
}
Output:
print_r(my_sqrt(16)."<br/>"); 4
print_r(my_sqrt(144)."<br/>"); 12
?>
PHP program to print factorial of number.

<?php

$num = 4;

$factorial = 1;

PHP program number.

for ($x=$num; $x>=1; $x--)


{
$factorial= $factorial * $x;

echo "Factorial of $num is $factorial";

?>

Output:

Factorial of 4 is 24
Write PHP program to print Fibonacci series

<?php

$num = 0;
$n1 = 0;
$n2 = 1;

echo "<h3>Fibonacci series for first 10 numbers:</h3>";


echo "\n";

echo $n1.' '.$n2.' ';

while ($num<10)

{
$n3= $n2+ $n1:
echo $n3.' ';
$n1 = $n2; Output:
$n2 = Sn3;
$num= $num+1; Fibonacci series for first 12 numbers:

} 0 1 1 2 3 5 8 13 21 34

You might also like