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

Unit I

The document discusses PHP programming including its history, uses, advantages, syntax, variables, data types, operators, and constants. It provides details on PHP's server-side scripting capabilities and how it can be used to manage dynamic content and databases.

Uploaded by

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

Unit I

The document discusses PHP programming including its history, uses, advantages, syntax, variables, data types, operators, and constants. It provides details on PHP's server-side scripting capabilities and how it can be used to manage dynamic content and databases.

Uploaded by

mehvishk132
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 48

Web Based Application Development

With PHP

Subject code :22619


UNIT I
Expression And Control Statements in PHP
1.1 History Of PHP
PHP started out as a small open source project that evolved as
more and more people found out how useful it was. Rasmus
Lerdorf unleashed the first version of PHP way back in 1994.
● PHP is a server side scripting language that is embedded in
HTML. It is used to manage dynamic content, databases,
session tracking, even build entire e-commerce sites.
● It is integrated with a number of popular databases, including
MySQL, PostgreSQL, Oracle, Sybase, Informix, and
Microsoft SQL Server.
What is PHP used for?
PHP programming can be used to create most things that a software
developer needs. However, there are three main areas in which it thrives.
● Server-side scripting:
Server-side Script is PHP’s main strength. If you are just learning to
code and want to explore server-side scripting, PHP is a great
language to learn. To get cracking with PHP server-side scripting
you’ll need to have a PHP parser, web server and web browser.
● Command-line scripting
Command-line scripting is ideal for scripts made using cron (Linux)
or Task Scheduler (Windows). It is also great for simple text
processing.
● Writing desktop applications
PHP is probably not the best language to use to create desktop
applications but for the advanced web developer, it provides you
with many more options than its competitors.
Advantages of PHP
● It is cross-platform: As mentioned above, PHP can be run on any
major operating system, so you don’t have to worry about compatibility.
This also means that you can work on a project team and not have to
worry about members being able to access code!
● It’s open-source: Open source means that PHP is a free programming
language, so you don’t have to worry about additional costs when
building your project
● Many developers understand it: The longevity of PHP means there’s
already a large community out there to support you, and a large amount
of legacy code to help you get started with projects.
● It works brilliantly with HTML: PHP can help simplify your
projects and works seamlessly with this dominant programming
language.
● As a language, it is relatively easy to learn: Because of its
simplicity, PHP is quicker and easier to pick up than some other
alternatives.
● There are plenty of tools available: There are tools to help you
with just about anything for PHP, from integration, code hinting,
syntax highlighting and more, there is a lot of support for you.
● It offers great load times for websites: With website
performance becoming more and more tied to speed, PHP’s quick
load can really help you succeed.
PHP Syntax
A PHP script can be placed anywhere in the document.
A PHP script starts with <?php and ends with ?>
<?php
// PHP code goes here
?>
The default file extension for PHP files is ".php".
A PHP file normally contains HTML tags, and some PHP scripting code.
we have an example of a simple PHP file, with a PHP script that uses a built-in
PHP function "echo" to output the text "Hello World!" on a web page
<!DOCTYPE html>
<html>
<body>
<h1>My first PHP page</h1>
<?php
echo "Hello World!";
?>
</body>
</html>
PHP statements end with a semicolon (;).
1.2 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. PHP has its own way of declaring
and storing variables.
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:
● Any variables declared in PHP must begin with a dollar sign ($), followed by
the variable name.
● A variable can have long descriptive names (like $factorial, $even_nos) or
short names (like $n or $f or $x)
● A variable name can only contain alphanumeric characters and
underscores (i.e., ‘a-z’, ‘A-Z’, ‘0-9, and ‘_’) in their name. Even it
cannot start with a number.
● A constant is used as a variable for a simple value that cannot be
changed. It is also case-sensitive.
● Assignment of variables is done with the assignment operator,
“equal to (=)”. The variable names are on the left of equal and the
expression or values are to the right of the assignment operator
‘=’.
● One must keep in mind that variable names in PHP names must
start with a letter or underscore and no numbers.
● PHP is a loosely typed language, and we do not require to
declare the data types of variables, rather PHP assumes it
automatically by analyzing the values. The same happens
while conversion. No variables are declared before they are
used. It automatically converts types from one type to
another whenever required.
● PHP variables are case-sensitive, i.e., $sum and $SUM are
treated differently.
Data types used by PHP to declare or construct variables:
● Integers
● Doubles
● NULL
● Strings
● Booleans
● Arrays
● Objects
<?php

// These are all valid declarations


$val = 5;
$val2 = 2;
$x_Y = "WEB Based Application";
$_X = "WBP";

// This is an invalid declaration as it


// begins with a number
$10_ val = 56;

// This is also invalid as it contains


// special character other than _
$f.d = "num";

?>
Local variables: The variables declared within a function are called local variables to that function and
have their scope only in that particular function. In simple words, it cannot be accessed outside that
function. Any declaration of a variable outside the function with the same name as that of the one
within the function is a completely different variable. We will learn about functions in detail in later
articles. For now, consider a function as a block of statements.
<?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";
?>
● 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";
?>
Static variable: 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.
<?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();
?>
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
Arithmetic Operators
The PHP arithmetic operators are used with numeric values to perform common
arithmetical operations, such as addition, subtraction, multiplication etc.
<?php
$x = 29; // Variable 1
$y = 4; // Variable 2
// Some arithmetic operations on
// these two variables
echo ($x + $y), "\n";
echo($x - $y), "\n";
echo($x * $y), "\n";
echo($x / $y), "\n";
echo($x % $y), "\n";
?>
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.
Comparison Operators
The PHP comparison operators are used to compare two values (number or string).
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.
Logical Operators
The PHP logical operators are used to combine conditional statements.
String Operators
PHP has two operators that are specially designed for strings.
Array Operators
The PHP array operators are used to compare arrays.
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.

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. Note:
Defining case-insensitive constants was deprecated in
PHP 7.3. PHP 8.0 accepts only false, the value true will
produce a warning.
Example
Create a constant with a case-sensitive name:
define("GREETING", "Welcome to W3Schools.com!");
echo GREETING;
Create a constant with a case-insensitive name:
define("GREETING", "Welcome to W3Schools.com!", true);
echo greeting;
Decision Making
PHP allows us to perform actions based on some type of conditions
that may be logical or comparative. Based on the result of these
conditions i.e., either TRUE or FALSE, an action would be
performed as asked by the user. It’s just like a two- way path. If you
want something then go this way or else turn that way. To use this
feature, PHP provides us with four conditional statements:
● if statement
● if…else statement
● if…elseif…else statement
● switch statement
if Statement: This statement allows us to set a condition. On
being TRUE, the following block of code enclosed within the if
clause will be executed.
Syntax :
if (condition){// if TRUE then execute this code}
<?php
$x = 12;
if ($x > 0) { echo "The number is positive"; }
?>
if…else Statement: We understood that if a condition will hold i.e.,
TRUE, then the block of code within if will be executed. But what if the
condition is not TRUE and we want to perform an action? This is where
else comes into play. If a condition is TRUE then if block gets executed,
otherwise else block gets executed.
Syntax:
if (condition) {// if TRUE then execute this code}
else{// if FALSE then execute this code}
Example:
<?php
$x = -12;
if ($x > 0) { echo "The number is positive"; }
else{ echo "The number is negative"; }
?>
if…elseif…else Statement: This allows us to use multiple if…else
statements. We use this when there are multiple conditions of
TRUE cases.
Syntax:
if (condition) {// if TRUE then execute this code}
elseif {// if TRUE then execute this code}
elseif {// if TRUE then execute this code}
else {// if FALSE then execute this code}
<?php
$x = "August";
if ($x == "January") { echo "Happy Republic Day";}
elseif ($x == "August") { echo "Happy Independence Day!!!";}
else{ echo "Nothing to show";}
?>
switch Statement: The “switch” performs in various cases i.e., it has
various cases to which it matches the condition and appropriately
executes a particular case block. It first evaluates an expression and
then compares with the values of each case. If a case matches then the
same case is executed. To use switch, we need to get familiar with two
different keywords namely, break and default.
1. The break statement is used to stop the automatic control flow
into the next cases and exit from the switch case.
2. The default statement contains the code that would execute if
none of the cases match.
Syntax:
switch(n) {
case statement1:
code to be executed if n==statement1;
break;
case statement2:
code to be executed if n==statement2;
break;
case statement 3:
code to be executed if n==statement3;
break;
case statement4:
code to be executed if n==statement 4;
break;
Default: code to be executed if n != any case;
<?php case "April": case "August":
echo "Its August";
$n = "February"; echo "Its April"; break;
switch($n) { break; case "September":
case "January": echo "Its September";
case "May": break;
echo "Its January"; echo "Its May"; case "October":
break; break; echo "Its October";
break;
case "February": case "June": case "November":
echo "Its February"; echo "Its June"; echo "Its November";
break; break;
break; case "December":
case "March": case "July": echo "Its December";
echo "Its March"; echo "Its July"; break;
break; default:
break; echo "Doesn't exist";}?>
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
while Loop
The while loop executes a block of code as long as the
specified condition is true.
Example
Print $i as long as $i is less than 6:
$i = 1;
while ($i < 6) {
echo $i;
$i++;
}
do while Loop
The do...while loop will always execute the block of code at least once, it
will then check the condition, and repeat the loop while the specified
condition is true.
Example
Print $i as long as $i is less than 6:
$i = 1;
do {
echo $i;
$i++;
} while ($i < 6);
Example
Set $i = 8, then print $i as long as $i is less than 6:
$i = 8;
do {
echo $i;
$i++;
} while ($i < 6);
For Loop
The for loop is used when you know how many times the script
should run.
Syntax
for (expression1, expression2, expression3) {
// code block}
This is how it works:
● expression1 is evaluated once
● expression2 is evaluated before each iteration
● expression3 is evaluated after each iteration
Example
Print the numbers from 0 to 10:
for ($x = 0; $x <= 10; $x++) {
echo "The number is: $x <br>";
}
Example Explained
1. The first expression, $x = 0;, is evaluated once and sets a counter to
0.
2. The second expression, $x <= 10;, is evaluated before each iteration,
and the code block is only executed if this expression evaluates to
true. In this example the expression is true as long as $x is less than,
or equal to, 10.
3. The third expression, $x++;, is evaluated after each iteration, and in
this example, the expression increases the value of $x by one at each
iteration.
The foreach Loop on Arrays
The most common use of the foreach loop, is to loop through the
items of an array.
Example
$colors = array("red", "green", "blue", "yellow");
foreach ($colors as $x) {
echo "$x <br>";
}
Important Questions :
1. Describe advantage of PHP.
2. Write syntax of PHP.
3. Write down rules for declaring PHP variable.
4. Explain different loops in PHP with example.
5. List types of variables.Explain any one type in detail with example.
6. Explain constant with example.
7. List uses of PHP.(Any Eight)

You might also like