Q) Write a note on PHP and
Explain its features
PHP was originally
created by Rasmus Lerdorf
in 1995. The main
implementation of PHP
is now produced by The PHP Group
and serves as the formal reference to the PHP language. PHP is free software
released under the PHP License, which is incompatible with the GNU General
Public License (GPL)
due to restrictions
on the usage
of the term
PHP. While PHP
originally stood for “Personal
Home Page”, it is now said to stand for “PHP: Hypertext Preprocessor”, a
recursive acronym.
Characteristics of PHP
The main characteristics of PHP are:
•PHP is web-specific and open source
•Scripts are embedded into static HTML files
•Fast execution of scripts
•Fast access to the database tier of applications
•Supported by most web servers and operating systems
•Supports many standard
network protocols libraries
available for IMAP,
NNTP, SMTP, POP3
•Supports many database management systems libraries available for
UNIX DBM, MySQL, Oracle
•Dynamic Output any text, HTML XHTML and any other XML file
•Also Dynamic Output images, PDF files and even Flash movies
•Text processing features,
from the POSIX
Extended or Perl
regular expressions to
parsing XML documents
•A fully featured programming language suitable for complex systems
development
Q)
What is a Variable? What are the rules to declare a variable in PHP?
Variable:
A
variable is a special container that can “holds” a value, such as a
number, string, object, array, or a Boolean. Variables are fundamental to
programming.
Rules
to declare a Variable:
1. A variable
consists of a name, preceded by a dollar sign ($).
2. Variable
names can include letters, numbers, and the underscore character ( _ ), but
they cannot include spaces.
3. Names must
begin with a letter or an underscore.
4. A semicolon
(;) is used to end the declaration of variable statement.
5. When we
declare a variable, we usually assign a value to it in the same statement.
Examples:
$a; $num1 = 8;
Q)
Explain Global Variable and Superglobal Variable.
Global
Variables: these variables are used to connect scripts to
each other. (that is, one script calls the other or includes the other), there
will be just one value for shared variable.
If the $name variable is defined
as a global variable in both scriptA.php
and scriptB.php, and these scripts
are connected to each other.
Superglobal
Variables: In addition to global variables of your own creation, PHP has several
predefined variables called superglobals. These variables are always present,
and their values are available to all scripts. The following are the superglobals
variables:
·
$_GET contains any variables provided to a
script through the GET method.
·
$_POST contains any variables provided to a
script through the POST method.
·
$_COOKIE contains any variables provided to a
script through a cookie.
·
$_FILES contains any variables provided to a
script through file uploads.
·
$_SERVER contains information such as headers,
file paths, and script locations.
·
$_ENV contains any variables provided to a
script as part of the server environment.
·
$_REQUEST contains any variables provided to a
script via GET, POST, or
COOKIE input mechanisms.
·
$_SESSION contains any variables that are
currently registered in a session.
Q)
What are the different data types available in PHP script?
PHP automatically determines the
data type at the time data is assigned to each variable.
Table shows the eight standard
data types available in PHP.
Q) Explain Operator, Operand and Expression.
Operator:
An
operator is a symbol or series of symbols that used to performs an action, and
usually produces a new value.
Operand: An operand
is a value used in conjunction with an operator. There are usually two or more
operands to one operator.
Example: (4 + 5)
Expression:
The
combination of operands with an operator to produce a result is called an expression.
An expression is any combination
of functions, values, and operators that resolves to a value.
Example: $user=(4 + 5)
Q)
Explain different types of operators available in PHP.
1. The Assignment Operator: The
assignment operator consists of the single character: =. The assignment operator
takes the value of the right-side operand and assigns it to the left-side operand.
Example: $name = “Shaik”;
2. Arithmetic Operators: The arithmetic operators perform arithmetic
operations.
Example:
3. The Concatenation Operator: The
concatenation operator is represented by a single period (.). Treating both operands
as strings, this operator appends the right-side operand to the left-side operand.
Example: “hello”.” world” returns “hello
world”
4. Combined Assignment Operators: A combined
assignment operator consists of a standard operator symbol followed by an equal
sign.
Example: $x = 4;
$x = $x + 4; // $x now equals 8
5. Incrementing and Decrementing Operator: PHP provides
some special operators that allow to add or subtract the integer constant 1
from an integer variable, assigning the result to the variable itself. These
are known as the post-increment and post-decrement operators.
Example $x++; // $x
is incremented by 1
$x--; // $x is decremented by 1
If you use the post-increment or
post-decrement operators in conjunction with a conditional operator, the
operand is modified only after the first operation has finished:
$x = 3;
$y = $x++ +
3;
In this instance, $y first
becomes 6 (the result of 3 + 3), and then $x is incremented.
PHP also provides the pre-increment and pre-decrement operators. These operators behave in the same way as
the post-increment and post-decrement operators, but they are written with the
plus or minus symbols preceding the variable:
EXAMPLE:
++$x; // $x is incremented by 1
--$x; // $x is decremented by 1
6. Comparison Operators: Comparison
operators perform comparative tests using their operands and return the Boolean
value true if the test is successful or false if the test fails
The == operator tests
equivalence, whereas the = operator assigns value. Also, remember that ===
tests equivalence with regard to both value and type.
7. Logical Operators: Logical operators test combinations of Boolean
values.
Example:
8. Operator Precedence: When you use an operator within an expression,
the PHP engine usually reads your expression from left to right.
The following is a list of the
operators covered in this chapter in precedence order (those with the highest
precedence listed first):
1. ++, --,
(cast)
2. /, *, %
3. +, -
4. <, <=,
=>, >
5. ==, ===, !=
6. &&
7. ||
8. =, +=, -=,
/=, *=, %=, .=
9. and
10.
xor
11.
or
Q)
Explain the concept of Constants in PHP.
PHP use built-in define( ) function
to create a constant, which subsequently cannot be changed unless specifically
define( ) it again.
Syntax: define(“YOUR_CONSTANT_NAME”,
42);
The value we want to set can be
a number, a string, or a Boolean. By convention, the name of the constant
should be in capital letters.
Constants are accessed with the constant name only; no dollar symbol is required.
Example:
<?php
define(“THE_YEAR”, “2012”);
echo “It is the year “.THE_YEAR;
?>
Constants can be used anywhere
in your scripts, including in functions stored in external files.
Q)
Explain briefly about flow control functions in PHP.
1. The if Statement: The if statement evaluates an expression found
between parentheses. If this expression results in a true value, the statement
is executed. Otherwise, the statement is skipped entirely.
Syntax:
|
if
(expression)
{
//
code to execute if the expression evaluates to true
}
|
Example:
<?php
$mood = “happy”;
if ($mood == “happy”) {
echo “Shaik! I’m in a good mood!”;
}
?>
2. if –else Statement: We can define
an alternative block of code that should be executed if the expression are
testing evaluates to false. We can do this by adding else to the if statement:
Syntax:
|
if
(expression)
{ // code to execute if the expression
evaluates to true
}
else
{ // code to execute in all other cases
}
|
Example:
<?php
$mood = “sad”;
if ($mood == “happy”) {
echo “Shaik! I’m in a good mood!”;
} else {
echo “I’m in a $mood mood.”;
}
?>
3. elseif Statement: we can use an
if...elseif...else clause to test multiple expressions.
Syntax:
|
if
(expression)
{ //
code to execute if the expression evaluates to true
}
elseif
(another expression)
{ // code to execute if the previous
expression failed
//
and this one evaluates to true
}
else
{ //
code to execute in all other cases
}
|
Example:
<?php
$mood = “sad”;
if ($mood == “happy”) {
echo “Hooray! I’m in a good mood!”;
} elseif ($mood == “sad”) {
echo “Awww. Don’t be down!”;
} else {
echo “I’m neither happy nor sad, but $mood.”;
}
?>
4. The switch Statement: The switch statement is an alternative way of
changing flow, based on the evaluation of an expression. A switch statement
evaluates only one expression in a list of expressions, selecting the correct
one based on a specific bit of matching code.
Synatx:
|
switch
(expression)
{
case
result1:
// execute this if
expression results in result1
break;
case
result2:
// execute this if
expression results in result2
break;
default:
// execute this if no break
statement
// has been encountered
hitherto
}
|
EXAMPLE:
<?php
$mood = “sad”;
switch ($mood) {
case “happy”:
echo “Hooray! I’m in a good mood!”;
break;
case “sad”:
echo “Awww. Don’t be down!”;
break;
default:
echo “I’m neither happy nor sad, but $mood.”;
break; } ?>
5. Ternary Operator or the ?: Operator: The ?: or ternary operator is similar
to the if statement, except that it returns a value derived from one of two
expressions separated by a colon.
This
construct provides you with three parts of the whole, hence the name ternary.
The expression used to generate the returned value depends on the result of a
test expression:
Syntax:
|
(expression)
? returned_if_expression_is_true : returned_if_expression_is_false;
|
EXAMPLE:
<?php
$mood = “sad”;
$text = ($mood == “happy”) ? “I am in a good mood!” : “I am in a $mood
mood.”;
echo “$text”;
?>
Q)
Explain briefly about looping statements in PHP.
Loop statements are used to
perform repetitive tasks until a specified condition is achieved. Theseare 1) While 2) do..While 3) For
1. The while Statement: A while statement
executes for as long as the expression evaluates to true, over and over again
if need. Each execution of a code block within a loop is called iteration.
Syntax:
|
while
(expression)
{
//
do something
}
|
Example:
<?php $counter = 1;
while ($counter <= 12) {
echo $counter.” times 2 is “.($counter * 2).”<br />”;
$counter++;
} ?>
2. The do...while Statement: do..while loop the condition is tested AFTER
executing the statements within the loop.
Syntax:
|
do
{
//
code to be executed
} while (expression)
|
Example:
<?php $num = 1;
do { echo “The number is: “.$num.”<br />”;
$num++;
} while (($num > 200) && ($num < 400));
?>
3. The for Statement: With a for
statement, we can achieve series of events in a single line of code.
|
for
(initialization expression; test expression; modification
expression) {
//
code to be executed
}
|
Example:
<?php
for ($counter=1; $counter<=12; $counter++) {
echo $counter.” times 2 is “.($counter * 2).”<br />”;
}
?>
Q) Explain Break statement in PHP
The break statement enables to
break out of a loop based on the results of additional tests
Example:
<?php
for ($counter=1; $counter <=
10; $counter++) {
$temp = 4000/$counter;
echo “4000 divided by “.$counter.” is...”.$temp.”<br />”;
}
?>
Q)
Write a note on Nesting Loops
Loops can contain other loop
statements, as long as the logic is valid and the loops are tidy. The
combination of such statements proves particularly useful when working with
dynamically created HTML tables.
Example:
<?php
echo “<table style=\”border: 1px solid #000;\”> \n”;
for ($y=1; $y<=12; $y++) {
echo “<tr> \n”;
for ($x=1; $x<=12; $x++) {
echo “<td style=\”border: 1px solid #000; width: 25px;
text-align:center;\”>”;
echo ($x * $y);
echo “</td> \n”;
}
echo “</tr> \n”;
}
echo “</table>”;
?>
Q)
Write a brief description about function.(OR) What Is a Function?
A function is a
self-contained block of code that can be called by your scripts. When called,
the function’s code is executed and performs a particular task.
We can pass values to a function,
which then uses the values appropriately—storing them, transforming them,
displaying them, whatever the function is told to do. When finished, a function
can also pass a value back to the original code that called it into action.
Functions
come in two flavors:
a) Built-in functions
and
b) User-defined
functions
PHP has hundreds of built-in
functions.
Example: strtoupper(“Hello
Web!”);
If you want to pass information
to the function, you place it between these parentheses. A piece of information
passed to a function in
this way is called an argument.
Some functions require that more than one argument be passed to them, separated
by commas:
Q)
How to create user defined function in PHP.
User defined functions
in PHP enable coders to create custom block of codes for specific events.
Function declaration starts with the word function.
Synatx:
|
function
some_function($argument1, $argument2)
{
//function
code here
}
|
The name of the function follows
the function statement and precedes a set of parentheses. If your function
requires arguments, you must place comma-separated variable names within the
parentheses. These variables are filled by the values passed to your function.
Even if your function doesn’t require arguments, you must nevertheless supply
the parentheses.
Example:
<?php
function sum() //Declaring
User Defined function
{
$a=3;
$b=6;
$a=$a+$b;
echo $a;
}
sum();//Calling a function
?>
Q)
Explain Returning Values from User-Defined Functions
The return statement stops the
execution of the function and sends the value back to the calling code.
<?php
function addNums($firstnum,
$secondnum)
{
$result = $firstnum +
$secondnum;
return $result;
}
echo addNums(3,5);
//will print “8”
?>
It can be the result of an
expression:
return
$a/$b;
It can be the value returned by
yet another function call:
return
another_function($an_argument);
Q)
Explain Variable Scope in PHP
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:
1. Local variables
2. Global variables
3. Static variables
4. Function parameters
1. Local variables: A variable
declared within a PHP function is local and can only be accessed within that
function. (the variable has local scope):
<?php
$a = 5; // global scope function myTest()
{echo $a; // local scope}
myTest();
?>
The script above
will not produce
any output because
the echo statement refers to
the local scope variable $a,
which has not been assigned a value within this scope.
You can have local variables with the same name in different
functions, because local variables are only recognized by the function in which
they are declared.
Local variables are deleted as soon as the function is completed.
2. Global variables: Global scope
refers to any variable that is defined outside of any function.
Global variables can be accessed from any part of the script that is
not inside a function.
To access a global variable from within a function, use the global keyword:
<?php
$a = 5;
$b = 10;
function myTest()
{global $a, $b;
$b = $a + $b;
}
myTest();
echo $b;
?>
The script above will output 15.
PHP also stores all global variables in an array called
$GLOBALS[index]. Its index is the name of
the variable. This
array is also
accessible from within
functions and can
be used to update
global variables directly.
The example above can be rewritten as this:
<?php $a = 5; $b = 10;
function myTest()
{
$GLOBALS['b'] = $GLOBALS['a'] + $GLOBALS['b'];
}
myTest();
echo $b; ?>
3. Static variables: When a
function is completed, all of its variables are normally deleted. However,
sometimes you want a local variable to not be deleted.
To do this, use the statickeyword when you first declare the variable:
static $rememberMe;
Then, each time
the function is
called, that variable
will still have
the information it
contained from the last time the function was called.
Note:The variable is still local to the function.
4. Function parameters: A
parameter is a local variable whose value is passed to the function by the
calling code. Parameters are declared in a parameter list as part of the
function declaration:
function myTest($para1,$para2,...)
{//
function code}Parameters are also called arguments
Q) Explain more about Aruments
PHP Function Arguments: Argument is
like a variable. Information is sent through arguments. You can add as many
arguments as you need by separating each with a comma by function. They are
specified within the parenthesis inside the function name.
<?php
function Number($Number)
{
echo "Phone Number is
$Number"."<br/>";
}
Number("123223");
Number("234324");
Number("345435");
?>
OutputPhone Number is 123223
Phone Number is 234324
Phone Number is 345435
Passing More Than 1 Argument
You can pass more than 1 argument through a function. Consider the following example.Example
<?php
function Number($firstname,$lastname)
{
echo "Employee's full name is
$firstname $lastname"."<br/>";
}
Number("Alex","Anderson");
Number("John","Walker");
Number("David","Clark");
?>
Output
Employee’s full name is Alex AndersonEmployee’s full name is John Walker
Employee’s full name is David Clark
PHP Default Argument Value
When we pass variables as parameters in a function and we don’t specify the default argument value, then it takes the default value as argument.Example
<?php
function setage($minage = 20) {
echo "The height is : $minage <br>";
}
setage(25);
setage(); // will use the default value of
20
setage(40);
setage(60);
?>
Output
The height is : 25The height is : 20
The height is : 40
The height is : 60
Functions: Returning Values
A function may return values when we use it with return statement. Hence, it is more useful when making functions for calculations.Example
<?php
function Multiplication($x, $y)
{
$z = $x * $y;
return $z;
}
echo "5 * 10 = " . Multiplication(5,
10) . "<br>";
echo "7 * 13 = " .
Multiplication(7, 13) . "<br>";
echo "2 * 4 = " .
Multiplication(2, 4);
?>
Output
5091
8
Comments
Post a Comment