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

unit 2 PHP PDF

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

unit 2 PHP PDF

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

UNIT–II

PHP Programming Basics:


Syntax of PHP - Embedding PHP in HTML - Embedding HTML
in PHP. Introduction to PHP Variable-understanding Data Types-
Using Operators -Using Conditional Statements -If(), else if() and else
if condition Statement.
What is PHP:
PHP is a open source, interpreted and object oriented scripting
language i.e. executed at server side. It is used to develop web applications (an
application i.e. executed at server side an degenerates dynamic page).
▪ PHP is a server side scripting language.
▪ PHP is an interpreted language, i.e. there is no need
for compilation.
▪ PHP is an object-oriented language.
▪ PHP is an open-source scripting language.
▪ PHP is simple and easy to learn language.
PHP Features:
Performance: Script written in PHP executes much Faster
than those scripts written in other languages such as SP&ASP.
Open Source Software: PHP source code is free variable on the web,
you can developed.
All the version of PHP according to your requirement with out
paying any cost.
Platform Independent: PHP area variable for WINDOWS,
MAC, LINUX&UNIX Operating system. A PHP application
developed in one OS can be easily executed in other Os also.
Compatibility : PHP is compatible with almost all local server
used today like Apache
Embedded: PHP code can be easily embedded within
HTML tag sand script.
PHP WORKING:
What is PHP?
PHP is a open source, interpreted and object-oriented scripting language
i.e. executed at.
Server side it is used to develop web applications (an application
i.e. executed at server.
Side and generates dynamic page.
PHP is a open source, interpreted and object-oriented scripting language
i.e. executed at server side. It is used to develop web applications (an
application i.e. executed at server side and generates dynamic page).

▪ PHP is a server side scripting language.


▪ PHP is an interpreted language ,i.e. there is no need for
compilation.
▪ PHP is an object-oriented language.
▪ PHP is an open-source scripting language.
▪ PHP is simple and easy to learn language.
▪ PHP is a server side scripting language.
▪ PHP is an interpreted language, i.e. there is no need for
compilation.
▪ PHP is an object-oriented language.
▪ PHP is an open-source scripting language.
▪ PHP is simple and easy to learn language.
PHP Features:
Performance: Script written in PHP executes much faster then
those scripts written in Other languages such as JSP&ASP.
Open Source Software: PHP source code is free available on the
web, you can developed.
All the version of PHP according to your requirement with out
paying any cost.
Platform Independent: PHP area variable for WINDOWS,
MAC, LINUX&UNIX
Operating system APHP application developed in one OS can be easily
executed in other OS also.
Compatibility: PHP is compatible with almost all local servers used to
day like Apache, II Set.
Embedded: PHP code can be easily embedded with in
HTML tag sand script.

PHP WORKING:
The process of running a PHP script on a Web server looks like this:
1. A visitor request Web page by clicking a link, or typing the page’s
URL into the browser ’s address bar. The visitor might also send data
to
The Web server at the same time, either using a form embedded in a
Web page, or via AJAX (Asynchronous Java Script And XML).
2. The Web server recognizes that the requested URL is a PHP
script, and instructs the PHP engine to process and run the script.
3. The script runs, and when it’s finished it usually send an
HTML page to the Web browser, which the visitor then see on
their screen.
Case Sensitivity:
The names of user- defined classes and functions, as well as built-
in constructs and keywords such as echo, while, class, etc., are case-
insensitive. Thus, these three lines are equivalent:
Variables, on the other hand, are case - sensitive. That is, $name,
$NAME, and $NAME are three different variables.
Statements and Semicolons
A statement is a collection of PHP code that does something. It can
be as simple as a variable assignment or as complicated as a loop with
multiple exit points.
PHP uses semicolons to separate simple statements. A compound
statement that uses curly braces to mark a block of code, such as a
conditional test or loop, does not need a semi colon after a closing
brace. Unlike in other languages, in PHP the semicolon before the
closing brace is not optional:
Comments:
Comments give information to people who read your code, but they
are ignored by PHP. Even if you think you're the only person who will
ever read your code, it's a good idea to include comments in your
code—in retrospect, code you wrote months ago can easily look as
though a stranger wrote it.
$x=17;//store 17in to the variable $x
Literals
A literal is a data value that appears directly in a program. The
following are all literals in PHP:
2001
0xFE
1.4142
"Hello
World
" 'Hi'
T
r
u
e

N
u
l
l
Identifiers
An identifier is simply a name. In PHP, identifiers are used to name
variables, functions, constants, and classes. The first character of an
identifier must be either an ASCII letter (uppercase or lowercase), the
underscore character (_), or any of the characters between ASCII
0x7F and ASCII 0xFF. After the initial character, these characters and
the digits 0-9 are valid.
Variable names:
Variable names always begin with a dollar sign($) and are case-
sensitive. Here are some valid variable names:
$head_ count
$Maximum Force
$I_HEART_PHP
$_underscore
$ _int
Here are some illegal variable names:
$not valid
$|
$3wa
First example of PHP
<!DOCTYPE>
<html>
<body>
<? Php echo"<h2>Hello First PHP</h2>";?>
</body>
</html>
How to execute your first PHP program
• Typeinhttp://localhost/hello.phpatbrowserURL
• By default web page storage directory on local web server is
c:\wamp\ www\
PHP Echo
PHP echo is a language construct nota function, so you don't need to
use parenthesis with it. But if you want to use more than one
parameters, it is required to use parenthesis.
The syntax of PHP echo is given below:
echo(string $arg1[,string $...])
PHP echo statement can be used to print string, multiline strings,
escaping characters, variable, array etc.
Syntax:
Echo "Hello by PHP echo";
PHP echo: printing multiline string
< ? Php
Echo "Hello by PHP echo
This is multiline text
printed by PHP echo
statement “;
?>
Output:
Hello by PHP echo this is multiline text printed by PHP echo statement.
Difference between Print and echo command

Features Echo Print


Parameter echo can take more than Print only takes one parameter.
one parameter when used
without parentheses.
What It is In PHP, echo is not a In PHP, print is not a really function
function but a language but a language construct.
construct. However, it be haves like a
function in that it returns a
value

Return Echo does not return any Print always returns 1(integer)
Value value
Syntax Void echo(string$arg1 [, int print(string $avg)
string$... ] )Note that
echo($arg1,$arg2) is
invalid.

An example from the PHP for print


Command:$b? print "true" : print "false";
Echo with out parentheses can take multiple parameters, which get
concatenated:
echo" anda",1,2,3;//comma-separated with out parentheses
echo ("and a 123");
//just one parameter with parentheses print() can only take one
parameter:
print("anda1
23"); print
"and a 123";
One major difference is that echo can take multiple parameters to output.

E.g.: echo ‘a‘,' bar';//concatenatesthe2strings


print(‘a', 'bar’); //Fatal error
Data Types
PHP provides eight types of values, or data types. Four are scalar (single-
value) types:
integers, floating-point numbers, strings, and boolean. Two are
compound(collection)types: arrays and objects. The remaining two are
special types: resource and NULL
Integers
Integers are whole numbers, like1, 12, and256.Therangeofacceptable
values varies according to the details of your platform but typically
extends from -2,147,483,648 to +2,147,483,647. Specifically, the
range is equivalent to the range of the long data type of your C
compiler.
Ex: 1998 -641+33.
Floating-Point Numbers:
Floating-point numbers (often referred to as real numbers) represent
numeric values with decimal digits. Like integers, their limits depend
on your machine's details.
PHP floating- point numbers are equivalent to the range of the
double data type of your C compiler.
Ex: 3.14, 0.017, -7.1

Strings
Because strings are so common in web applications, PHP
includes
Core level support for creating and manipulating strings. A string is a
sequence of characters of arbitrary length. String literals are delimited
by either single or double quotes:
'
b
i
g

d
o
g
'

"
f
a
t

h
o
g
"

B
o
o
l
e
a
n
s
A Boolean value represents a "truth value"—it says whether
something is true or not. Like most programming languages, PHP
defines some values as true and others as false.
Arrays
An array holds a group of values, which you can identify by
position (a number, with zero being the first position) or some
identifying name (a string):
$person [0] ="Edison";
$person [1] ="Wankel";
$person [2]= "Crapper";
Objects
PHP supports object- oriented programming (OOP). OOP promotes
clean modular design, simplifies debugging and maintenance, and
assists with code reuse.
$abc =new Person;
Resources
Many modules provide several functions for dealing with the
outside world. For example, every database extension has at least a
function to connect to the data base, a function to send a query to the
data base, and a function to close the connection to the database.
$? php
$ fp = f open ("abc", "w");
Echo get_resource_type ($fp),//stream
$fp=f open("abc", "w");
Echo get_resource_type($fp);
$c=mysql_connect();
Echoget_resource_type($c)//my sql link?>NULL
There's only one value of the NULL data type. That value is a variable
through the case-insensitive keyword NULL
$aleph=null; //variable's value is gone
PHP Variables
A variable in PHP is a name of memory location that holds data. A
variable is a temporary storage that is used to store data temporarily.
In PHP, a variable is declared using $sign followed by variable name.
Syntax of declaring a variable in PHP is given below:
$variable
name=value;
Example:$f name,
$age
To initialize the variables, write as follows
$ fname = “Rahul”$age=35

Rules for PHP variables


1. A variable starts with the $sign, followed by the name of the variable.
2. Variable name must begin with a letter or the underscore character.
3. A variable name can only contain alpha-numeric characters
and underscores (A-z, 0-9,and _ )
4. A variable name should not contain spaces.
5. Variable names are case sensitive ($y and $Y are two
different variables)
PHP Variable:
Sum of two variables
<?php
$x=5;$y=6;
$
z
=
$
x
+
$
y
;

e
c
h
o

$
z
;
?>
Testing the Type of a Variable:
You can determine the type of a variable at any time by using PHP ’ s
get type() function. The get type(), pass in the variable whose type you
want to test. The function then returns the variable ’s type as a string.
• $test_ var; //Declares the $test_ var variable with out
initializing it echo get type( $test_var ) . “ <br / > ”; //
Displays “NULL”
• $test_var=15;
Echo get type($test_var ).“<br/>”;//Displays “integer”
• $test_var=8.23;
Echo get type($test_var ).“<br/>”;//Displays “double”
• $test_var=“Hello, world!”;
Echo get type($test_var ).“<br/>”;//Displays “string”
You can also test a variable for a specified at a type using PHP’s type
testing functions:
Function Description
is_int ( value ) Returns true if value is an
integer is_float ( value ) Returns true if value is a
float is_string( value ) Returns true if value is a
string is_bool( value ) Returns true if value is a
Boolean is_array( value ) Returns true if value is an
array is_object( value ) Returns true if value is an
object
is_resource( value ) Returns true if value is are
source is_null( value ) Returns true if value is
null
Changing a Variable’s Data Type
You can use PHP’s set type() function to change the type of a
variable while preserving the variable ’ s value as much as possible. To
use set type() ,pass in the name of the variable you want to alter,
followed by the type to change the variable to (in quotation marks).
• $test_var=8.23;
Echo $test_var .“<br/>”;//Displays “8.23”
• Set type($test_var, “string”);
Echo $test_var .“<br/>”;//Displays “8.23”
• Set type($test_var, “integer”);
Echo $test_var .“<br/>”;//Displays“8”
• Set type($test_var,“float”);
Echo $test_var .“<br/>”;//Displays“8”
• Set type($test_var,“boolean”);
Echo $test_var .“<br/>”;//Displays“1”
Reference the value of a variable:
Difference Between $var and $var in PHP
$$var uses the value of the variable whose name is the value of $var.
It means $$var is known as reference variable where as $var is normal
variable. It allows you to have a“ variable’ s variable”–the program
can create the variable name the same way it can create any other
string.
<?php $name="Rajeev";
$$name="Sa
njeev"; echo
$name."<br/
>";
echo$$name.
"<br/>";
echo
$Rajeev;
?>
Output:

R
a
j
e
e
S
a
n
j
e
e
v

S
a
n
j
e
e
v
PHP Is a Loosely Typed Language
We did not have to tell PHP which data type the variable is. PHP
automatically converts the variable to the correct data type, depending
on its value.
In a strongly typed programming language, we will have to declare
(define) the type and name of the variable before using it.
PHP Constants
PHP constants are name or identifier that can't be changed during the
execution of the script.PHP constants can be defined by 2 ways:
• Using define() function
• Using const keyword
PHP constants follow the same PHP variable rules. For example, it
can be started with letter or underscore only.
Conventionally, PHP constants should be defined in uppercase letters.
• Define (name, value, case-insensitive)
1. name: specifies the constant name
2. value: specifies the constant value
3. case- in sensitive: Default value is false. It means it is case
sensitive by default.
<?php define("MESSAGE", "Hello
PHP"); echo MESSAGE;
?>
<?php
define("MESSAGE", "Hello PHP", true); //not case
sensitive echo MESSAGE;
echo message;
?>
Output:
Hello PHP Hello PHP
<?php
Define ("MESSAGE" ," Hello PHP " , false); //case
sensitive echo MESSAGE;
echo message;
?>
Output: Hello PHP
Notice: Use of undefined constant message-as sum 'message' in
C:\wamp\www\vconstant3.php online 4message
PHP constant: const keyword The const key word defines constants at
compile time. It is a language construct not a function. It is bit faster
than define(). It is always case sensitive.
<?php
Const MESSAGE
=" Hello const by
PHP";
echo MESSAGE;
?>

Operators and Expressions Operators


Operator takes some value and does something (for instance, add them
together) Operator are written as punctuation symbols–like+,-.
Operator is a symbol that manipulates one or more values, usually
producing a new value in the process. Mean while, an expression in
PHP is anything that evaluates to a value; this can be any combination
of values, variables, operators, and functions. In the preceding example,
$x+$y is an expression. Here are some more example so f expressions:
$x+$y+$z
$x-$y$x5
true
get type ($test_var)
Expression
Expression is a bit of PHP that can be evaluated to produce a
value. Simplest expression are literals and variables. Literal values
evaluates to itself, while variable evaluates to the values to red in the
variable. Operator Types
Operator sin PHP can be grouped into ten types, as follows:
Arithmetic Perform common arithmetical:
Operations, such as addition and subtraction Assignment Assign
values to variables Bitwise Perform operations on individual bits in an
integer Comparison Compare values in a Boolean fashion true or false is
returned).
Affect error handling Incrementing/ Decrementing Increment or
decrement a variable’s value Logical Boolean operators such
as and, or, And not that can be used to Include or exclude.

Type Description
Arithmetic Performcommonarithmeticaloperations,suchasadditionan
dsubtraction
Assignment Assign values to variables
Bitwise Perform operations on individual bits in an integer

Comparison Compare values in a Boolean fashion (true or false is


returned)
Error Control Affect error handling
Incrementing/Decrem Increment or decrement a variable’s value
enting
Logical Booleanoperatorssuchasand,or,andnotthatcanbeusedtoi
ncludeorexclude
Arithmetic Operators:
In PHP, the arithmetic operators (plus, minus, and soon) work much
as you would expect, enabling you to write expression as though they
were simple equations. For example, $c =$a +$ b add s $a and $b and
assigns the result to $c. Here’s a full list of PHP’s arithmetic operators:
Operator Example Equation
+(addition) 6+3=9
-(subtraction) 6-3=3
*(multiplication) 6*3=18
/(division) 6/3=2
%(modulus) 6%3=0(theremainderof6/3)

Assignment Operators:
You’ve already seen how the basic assignment operator (=) can be used to
assign a value to a variable.
$test_var=8.23;
Bitwise Operators:
PHP’s bit wise operators let you work on the individual bits with in
integer variables. A bit with a value of 1 is said to be set, where as a bit
with a value of0 is unset (or not set).

Operator Description Example


&(And) Only bits set in both values are set in 14&3=2
the result 00001110&00000011=00000
010
(Or)Bits Bit set in either valuearesetintheresult 14|3=1500001110
00000011=00001111
^(Xor) Bitssetineithervalue(butnotboth)areseti 14^3=1300001110|00000011
n =00001101
theresult
~(Not) Bitssetinthevaluearenotsetintheresult,a 0=1
ndviceversa
<< Shiftsallbitsinthefirstvalueanumberofp 3<<2=1200000011<<2
(Shiftleft) lacestotheleft(specifiedbythesecondval =00001100
ue)
>> Shiftsallbitsinthefirstvalueanumberof 8>>2=200001000>>2
(Shiftright placestotheright(specifiedbythesecond =00000010
)
value)

ComparisonOperators
As you mightimagine from the name, comparis on operators let you
compare one operand with the other in various ways. If the comparis on test is
successful ,the expression evaluates to true; otherwise,it evaluates to false.
Operator Example Result
$x===$y true if $xequals $y; false
== otherwise
(equal)
==(equal)

!=or<>(notequal) $x!==$y true if $x does not equal


$y; false otherwise
$x===$y true if $x equals $y and
=== they are of the sametype;
false otherwise

(identic
al)

===(identical)
!==(notidentical) $x!==$y true if $x does not equal
$y or they are not of the
same
type; false otherwise
<(lessthan) $x<$y true if $x is lessthan $y;
false otherwise
>(greaterthan) $x>$y true if $x is greaterthan
$y;false otherwise
<=(lessthanorequalto) $x<=$y true if $x is less than or
equal to
$y;falseotherwise
>=(greaterthanorequalto) $x>=$y true if $x is greater than or
equal to $y; false
otherwise

The following examples show comparison operators inaction:


$x =23;
echo( $x< 24) .“<br /> ”;//Displays1 (true)
echo($x<“24”).“<br/>”;//Displays 1(true)because//PHP converts the
string to an integer
echo ( $x == 23 ) . “ <br / > ”; //
Displays 1 (true)
echo($x===23).“<br/>”;//Displa
ys1(true)
echo($x===“23 ”).“<br/>”;// Displays“”(false)because
//$xand “23”are notthe samedata type
echo ( $x > = 23 ) . “ <br / > ”; //
Displays 1 (true)
echo($x>=24).“<br/>”;//Display
s“”(false)
As you can see, comparison operators are commonly used to compare
two numbers (or strings converted to numbers). The == operator is also
frequently used to check that two strings are the same.
Incrementing/Decrementing Operators
They are written as two plussign sort wominus signs, respectively,
preceding or following a variable name, like so:
++$x;// Adds one to $x and then returns the result
$x++;//Returns $x and then adds one to it
–-$x;// Subtracts one from $x and then returns the result
$x–-;//Returns $x and then subtracts one fromit
$x=5; echo++$x; //Displays “6”(and $x now contains 6)
$x=5; echo$x++; //Displays “5”(and $x now contains6)
Logical Operators:
PHP’s logical operators work on Boolean values, a Boolean value is
either true or false.

Operator Example Result


&&(and) $x &&$y true if both $x and $y
evaluate to true ; false
otherwise
And $xand $y true if both $x and
$y evaluate to
true; false
otherwise
||(or) $x||$y true if either $x or
$y evaluates to true;false
otherwise
Or $x or $y true if either $x or $y
evaluates to true;false
otherwise
Xor $x xor$y true if $x or $y (but not
both) evaluates to true ;
false otherwise
! (not) !$x true if $x is false; false
if $x is true

Herearesomesimpleexamplesoflogicaloperators in action:
$x =2;
$y =3;
echo ( ($x > 1) && ($x <5) ) . “ <br / >”;
//Displays 1 (true)

echo( ($x== 2)or ($y== 0)) .“<br />


”;//Displays1 (true)
echo(($x==2)xor($y==3)).“<br/>”;//Displays“”(false)because both
//expressions are true
echo(!($x==5)).“<br/>”;// Displays1 (true) because// $x does not equal
StringOperators:
There ’ s really only one string operator, and that ’ s the
concatenation operator , . (dot). This operator simply takes two string
values ,and joins the right- hand string on to the left-hand one to make a
longer string.
For example:
echo“Amit,“.“notstirred”;// Displays“Amit,notstirred ”
Conditional Statements
PHP supports a number of traditional programming constructs for
controlling the flow of execution of a program. Conditional
statements, such as if/ else and switch, allow a program to execute
different pieces of code, or none at all, depending on some condition.
Loops, such as while and for,support the repeated execution of
particular code.
If statement
The if construct is one of the most important features of many
languages, PHP included.It allows for conditional execution of code
fragments. PHP features an if structure that is similar to that of C
Syntax:if (expression)statement
Expression is evaluated to its Boolean value. If b expression evaluates to
TRUE, PHP will execute statement, and if it evaluates to FALSE - it'll
ignore it.
Example: display a is bigger than b if
$a is bigger than $b: Code:
<?PHP
$a= 10;
$b=20;
if($a== 10)
{
print(“valueof$a=10");
}
if($b==10)
{
print(“valueof$bis20");
}
?>
Else:
else extends an if statement to execute a statement incase the expression in
the if statement evaluates to FALSE.
For example: display a is greaterthan b if $a is greaterthan $b, and a is
NOTgreaterthan b otherwise:
Code:
<?php
if($a>$b)
{
echo"a is greaterthan b";
}
else
{
echo"a is NOT greaterthan b";
}
?>
If else if else:
Else if, as its name suggests ,is a combination of if and else. Like else, it
extends an if statement to execute a different statement
<?php
$a=10;
$
b
=
2
0
;

i
f
(
$
a
>
$
b
)
{
echo"a isbiggerthan b";
}
elseif($a==$b)
{
echo"a isequalto b";
}
else{echo"aissmallerthanb";
}
?>

ONE MARK QUESTIONS:

1.What does PHP stand for?


A) Personal Home Page B) Preprocessor Hypertext
C) Preprocessor Home Page D) PHP Hypertext Preprocessor
Answer: D) PHP Hypertext Preprocessor
2. Which symbol is used to declare a variable in PHP?
A) @ B) $ C) & D) %
Answer: B) $
3. Which function is used to print in PHP?
A) echo() B) printf() C) print() D) All of the above
Answer: D) All of the above
4. Which of the following is a PHP superglobal variable?
A) $_GET B) $_POST C) $_SESSION D) All of the above
Answer: D) All of the above
5. How do you start a PHP block of code?
A) <?php. B) <php> C) <? D) php{}
Answer: A) <?php
6. Which function is used to get the length of a string in PHP?
A) strlen() B) strcount() C) count() D) length()
Answer: A) strlen()
7. Which of the following is the correct way to include a file in PHP?
A) include('filename.php'); B) require('filename.php');
C) Both A and B D) None of the above
Answer: C) Both A and B
8. What is the correct way to add a comment in PHP?
A) // B) /* */ C) # D) All of the above
Answer: D) All of the above
9. Which of the following is the correct syntax for a foreach loop in PHP?
A) foreach($array as $value) { } B) foreach($array in $value) { }
C) foreach($array with $value) { } D) foreach($array as $key => $value) { }
Answer: D) foreach($array as $key => $value) { }
10. Which of the following is used to create a constant in PHP?
A) define() B) constant() C) const() D) var()
Answer: A) define()
11.What does PHP stand for?
A) Personal Home Page B) Preprocessor Hypertext
C) Preprocessor Home Page D) PHP Hypertext Preprocessor
Answer: D) PHP Hypertext Preprocessor
12. Which symbol is used to declare a variable in PHP?
A) @ B) $ C) & D) %
Answer: B) $
13. Which function is used to print in PHP?
A) echo() B) printf() C) print() D) All of the above
Answer: D) All of the above
14. Which of the following is a PHP superglobal variable?
A) $_GET B) $_POST C) $_SESSION D) All of the above
Answer: D) All of the above
15. How do you start a PHP block of code?
A) <?php B) <php> C) <? D) php{}
Answer: A) <?php
16. Which function is used to get the length of a string in PHP?
A) strlen() B) strcount() C) count() D) length()
Answer: A) strlen()

17. Which of the following is the correct way to include a file in PHP?
A) include('filename.php'); B) require('filename.php');
C) Both A and B D) None of the above
Answer: C) Both A and B
18. What is the correct way to add a comment in PHP?
A) // B) /* */ C) # D) All of the above
Answer: D) All of the above
19. Which of the following is the correct syntax for a foreach loop in PHP?
A) foreach($array as $value) { } B) foreach($array in $value) { }
C) foreach($array with $value) { } D) foreach($array as $key => $value) { }
Answer: D) foreach($array as $key => $value) { }
20. Which of the following is used to create a constant in PHP?
A) define() B) constant() C) const() D) var()
Answer: A) define()
21.Which of the following is the correct way to embed PHP in an HTML file?
A) <php> ... </php> B) <?php ... ?> C) <script> ... </script> D) <php
code="...">
Answer: B) <?php ... ?>
22. What is the primary purpose of embedding PHP in HTML?
A) To style HTML elements B) To generate dynamic content
C) To create JavaScript functions D) To include CSS styles
Answer: B) To generate dynamic content
23. Where does PHP code execute when embedded in an HTML file?
A) On the client-side B) In the browser C) On the server-side D) On the
database
Answer: C) On the server-side
24. Which of the following tags is used to start a PHP block in an HTML file?
A) <script> B) <php> C) <?php D) <php?>
Answer: C) <?php
25. Which of the following is correct to output HTML from PHP in an embedded
block?
A) echo "<h1>Hello World</h1>"; B) echo "<h1>Hello
World</h1>"
C) print("<h1>Hello World</h1>") D) Both A and C
Answer: D) Both A and C
26. How can you embed a PHP variable inside an HTML tag?
A) <p><?php $variable ?></p> B) <p>$variable</p>
C) <p>{{ $variable }}</p> D) <p><?php echo $variable;
?></p>
Answer: D) <p><?php echo $variable; ?></p>
27. What happens if you mix HTML and PHP incorrectly?
A) The HTML will not display B) The PHP code will be
treated as plain text
C) The server will ignore the PHP D) All of the above
Answer: B) The PHP code will be treated as plain text
28. Which of the following is an incorrect way to embed PHP within HTML?
A) <?php echo "Hello, World!"; ?> B) <p><?php echo "Hello,
World!"; ?></p>
C) <div><?php echo "Hello"; ?></div> D) <h1><php echo "Hello";
?></h1>
Answer: D) <h1><php echo "Hello"; ?></h1>
29.Which symbol is used to declare a variable in PHP?
A) @ B) $ C) % D) &
Answer: B) $
30. Which of the following is a valid variable name in PHP?
A) $1name B) $name_1 C) $_name D) Both B and C
Answer: D) Both B and C
31. In PHP, variables are?
A) Case-sensitive B) Case-insensitive C) Always uppercase
D) Case-insensitive except for numbers
Answer: A) Case-sensitive
32. Which of the following is the correct way to assign a value to a variable in
PHP?
A) $name = "John"; B) name = "John"; C) $name == "John"; D) var name =
"John";
Answer: A) $name = "John";
33. What is the default value of an uninitialized variable in PHP?
A) 0 B) null C) false D) Undefined
Answer: B) null

34. Which of the following is not a valid PHP variable name?


A) $myVar B) $_myvar C) $123var D) $var_name
Answer: C) $123var
35. What is the correct way to concatenate two strings in a PHP variable?
A) $var1 + $var2 B) $var1 . $var2 C) $var1 & $var2 D) $var1 $var2
Answer: B) $var1 . $var2
36. What type of variable scope exists within functions in PHP by default?
A) Global B) Local C) Static D) Public
Answer: B) Local
37. Which of the following is used to make a variable global inside a function?
A) global $var; B) $GLOBALS["var"]; C) Both A and B D) None of the
above
Answer: C) Both A and B
38. Which of the following is the correct syntax to declare a variable that cannot be
changed in PHP?
A) define("VAR", "value"); B) const VAR = "value"; C) Both A and B D)
None of the above
Answer: C) Both A and B
39.Which of the following is not a PHP data type?
A) Integer B) Float C) String D) Character
Answer: D) Character
40. Which function is used to get the data type of a variable in PHP?
A) gettype() B) typeof() C) datatype() D) checktype()
Answer: A) gettype()
41. What is the data type of the variable $var = 10; in PHP?
A) Integer B) String C) Float D) Boolean
Answer: A) Integer
42. What is the correct data type for the value 10.5 in PHP?
A) Integer B) Float C) Double D) String
Answer: B) Float
43. Which of the following is a valid boolean value in PHP?
A) yes B) 1 C) true D) True
Answer: C) true

44. What is the output of the following code: echo gettype("10");?


A) integer B) float C) string D) double
Answer: C) string
45. Which of the following data types does PHP automatically assign when you
store a value like NULL in a variable?
A) Boolean B) Null C) Undefined D) String
Answer: B) Null
46. Which of the following is a compound data type in PHP?
A) String B) Array C) Integer D) Float
Answer: B) Array
47. What is the default data type of a variable that contains an array in PHP?
A) Array B) Object C) Mixed D) String
Answer: A) Array
48. Which of the following is used to explicitly cast a variable to a specific data
type in PHP?
A) (int)$var B) (string)$var C) (float)$var D) All of the above
Answer: D) All of the above
49.Which operator is used to concatenate two strings in PHP?
A) + B) . C) & D) *
Answer: B) .
50. Which of the following is the assignment operator in PHP?
A) == B) = C) === D) =>
Answer: B) =
51. Which operator is used to compare two values for equality in PHP?
A) = B) === C) == D) !=
Answer: C) ==
52. What is the result of the expression $x = 5 % 2; in PHP?
A) 2 B) 0 C) 1 D) 5
Answer: C) 1
53. Which of the following is the logical AND operator in PHP?
A) && B) || C) ! D) &
Answer: A) &&
54. What is the result of the following expression: 10 > 5 && 2 < 3;?
A) true B) false C) null D) 1
Answer: A) true
55. Which operator is used for exponentiation in PHP?
A) ^ B) ** C) ^^ D) *
Answer: B) **
56. What does the !== operator do in PHP?
A) Checks if two values are not equal
B) Checks if two values are identical (same value and type)
C) Checks if two values are not identical (either different value or type)
D) Checks if two variables point to the same object
Answer: C) Checks if two values are not identical (either different value or type)
57. Which operator is used to increment a variable by 1 in PHP?
A) + B) ++ C) -- D) +=
Answer: B) ++
58. What is the result of the expression 3 + 4 * 2; in PHP?
A) 14 B) 11 C) 8 D) 12
Answer: B) 11(Order of operations: multiplication before addition)
59.Which of the following is the correct syntax for an if statement in PHP?
A) if [condition] { } B) if (condition) { } C) if {condition} ( ) D) if
(condition); { }
Answer: B) if (condition) { }
60. Which keyword is used to specify the alternative block of code if the if
condition is false?
A) elseif B) else C) then D) default
Answer: B) else
61. Which of the following is used to check multiple conditions in an if statement
in PHP?
A) && B) || C) == D) Both A and B
Answer: D) Both A and B
62. What is the correct syntax for an else if block in PHP?
A) else if (condition) { } B) elseif (condition) { } C) else (condition) { } D)
Both A and B
Answer: D) Both A and B
63. Which of the following is a ternary operator used for conditional statements in
PHP?
A) ?: B) ?? C) == D) ::
Answer: A) ?:
64. What is the output of the following code? echo (5 > 3) ? "True" : "False";
A) True B) False C) 5. D) 3
Answer: A) True
65. What is the purpose of the switch statement in PHP?
A) To compare multiple conditions with a single value
B) To handle looping in the code
C) To execute a block of code if a certain condition is true
D) To terminate the execution of a program
Answer: A) To compare multiple conditions with a single value
66. Which keyword is used to exit a case in a switch statement in PHP?
A) exit B) continue C) break D) stop
Answer: C) break
67. What will happen if no break is used in a switch statement?
A) The code will throw an error B) The execution will stop at that case
C) The next case will also execute D) Only the first case will execute
Answer: C) The next case will also execute
68. Which of the following conditional statements allows you to check multiple
conditions and execute one of several blocks of code in PHP?
A) if...else B) switch C) while D) for
Answer: B) switch
69.Which of the following is the correct syntax for an if statement in PHP?
A) if condition { } B) if (condition) { } C) if [condition] { } D) if
{condition} ( )
Answer: B) if (condition) { }
70. Which of the following will correctly check if a variable $x is greater than 10?
A) if $x > 10 { } B) if (x > 10) { } C) if ($x > 10) { } D) if ($x => 10) {
}
Answer: C) if ($x > 10) { }
71. What will happen if the condition inside an if statement evaluates to false?
A) The code inside the if block is executed B) The code inside the if block is
skipped
C) The program will stop D) A syntax error will occur
Answer: B) The code inside the if block is skipped

72. Which of the following is true about the if statement in PHP?


A) It can only have one condition B) It must always be followed by an else
statement
C) It can be nested inside another if statement D) It cannot be used without an
else statement
Answer: C) It can be nested inside another if statement
73. Which of the following is a valid condition in an if statement?
A) if (5 == 5) { } B) if (5 = 5) { } C) if (5 === "5") { } D) Both A and C
Answer: D) Both A and C
74. What is the output of the following code? if (3 < 5) { echo "True"; } else {
echo "False"; }
A) True B) False C) 3 D) No output
Answer: A) True
75. How do you check if a variable $x is equal to 10 in an if statement?
A) if ($x = 10) { } B) if ($x == 10) { } C) if ($x === 10) { } D) Both B and C
Answer: D) Both B and C
76. Which of the following is not required for a basic if statement in PHP?
A) Curly braces {} B) Condition inside parentheses () C) A valid condition
D) A semicolon after the if statement
Answer: D) A semicolon after the if statement
75. Which operator would you use inside an if statement to check if two conditions
are true?
A) && B) || C) == D) ++
Answer: A) &&
76. What will be the output of the following code? if (false) { echo "Yes"; } else {
echo "No"; }
A) Yes B) No C) Nothing D) False
Answer: B) No
77.Which of the following is the correct syntax for an else if statement in PHP?
A) else if condition { } B) else if (condition) { } C) elseif (condition) { } D)
Both B and C
Answer: D) Both B and C

78. What will the following code output?


$x = 10;
if ($x < 5) {
echo "Less than 5";
} elseif ($x < 15) {
echo "Less than 15";
} else {
echo "15 or more";
}
A) Less than 5 B) Less than 15 C) 15 or more D) No output
Answer: B) Less than 15
79. What is the purpose of using else if in PHP?
A) To replace the if statement B) To create a new function
C) To check multiple conditions sequentially D) To terminate a loop
Answer: C) To check multiple conditions sequentially
80. Which of the following correctly checks multiple conditions using else if?
$age = 20;
if ($age < 18)
{
echo "Minor";
}
else if ($age < 65)
{
echo "Adult";
}
else
{
echo "Senior";
}
A) Minor B) Adult C) Senior D) No output
Answer: B) Adult
81. How many else if statements can you use in a single if construct?
A) Only one B) As many as needed C) None D) Two
Answer: B) As many as needed

82. What will be the output of the following code?


$a = 5;
if ($a > 10) {
echo "High";
} elseif ($a == 5) {
echo "Medium";
} else {
echo "Low";
}
A) High B) Medium C) Low D) No output
Answer: B) Medium
83. What is the effect of not including else if in a series of conditions?
A) The code will not run B) Only the first if condition will be checked
C) Only the last condition will execute D) None of the above
Answer: B) Only the first if condition will be checked
84. Which of the following conditions will be true for this code?
$score = 80;
if ($score >= 90) {
echo "A";
} elseif ($score >= 80) {
echo "B";
} else {
echo "C";
}
A) A B) B C) C D) No output
Answer: B) B
85. In an if...else if...else construct, which part is executed if none of the conditions
are true?
A) The if block B) The else if block C) The else block D) None
of the blocks
Answer: C) The else block

86. Which of the following is the correct way to write multiple conditions using
else if?
A) if (a) { } elseif (b) { } B) if (a) { } else if (b) { } else { }
C) if (a) { } else (b) { } D) Both A and B
Answer: D) Both A and B

5-Mark Questions

1. Explain the basic syntax of PHP.

2. How can PHP be embedded in HTML? Provide an example.

3. What are data types in PHP? List and briefly describe any two.

4. Describe the usage of variables in PHP.

5. Explain the concept of conditional statements in PHP with an example.

10-Mark Questions

1. Discuss the different data types in PHP with examples.

2. Explain PHP operators and their types with examples.

3. Write a detailed note on the usage of if, else, and else if statements in PHP,
including syntax and examples.

4. Describe the process of embedding PHP in HTML and embedding HTML


within PHP with examples.

You might also like