unit 2 PHP PDF
unit 2 PHP PDF
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
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.
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
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;
?>
Type Description
Arithmetic Performcommonarithmeticaloperations,suchasadditionan
dsubtraction
Assignment Assign values to variables
Bitwise Perform operations on individual bits in an integer
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).
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)
(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
Herearesomesimpleexamplesoflogicaloperators in action:
$x =2;
$y =3;
echo ( ($x > 1) && ($x <5) ) . “ <br / >”;
//Displays 1 (true)
i
f
(
$
a
>
$
b
)
{
echo"a isbiggerthan b";
}
elseif($a==$b)
{
echo"a isequalto b";
}
else{echo"aissmallerthanb";
}
?>
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
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
3. What are data types in PHP? List and briefly describe any two.
10-Mark Questions
3. Write a detailed note on the usage of if, else, and else if statements in PHP,
including syntax and examples.