ch-2 PHP
ch-2 PHP
ch-2 PHP
BASICS OF PHP
PHP Structure and Syntax:
PHP Structure:
PHP programs are written using a text editor, such as Notepad or WordPad, just like HTML
pages.
However, PHP pages, for the most part, end in a .php extension.
This extension signifies to the server that it needs to parse the PHP code before sending the
resulting HTML code to the viewer’s Web browser.
The structure of PHP is described below
<?php
………………………
No. of statements goes here
………………………
?>
In above structure <?php indicates the opening of the PHP Scripts.
?> indicates the ending of the PHP Scripts and in between these two we can place the
number of statements that is used to execute the PHP Script.
Example:
<?php
echo “Rahul Patel”;
?>
As we have seen in the previous example that PHP Script is started with php tag (<?php) and
end with the (?>) tag.
This PHP Script is implementing the one statement with “echo”.
This indicates “echo” is a output statement in the PHP and the string “Rahul Patel” will be
display on the webpage
Note one thing in the above example that it is terminated with the semicolon (;).
So, in PHP every statement terminates with the semicolon.
We can embed the above PHP Script in the HTML as like below
<html>
<head>
<title>
My First PHP Page
</title>
</head>
<body>
<?php
echo "Rahul Patel";
?>
</body>
</html>
Comments in PHP:
PHP also supports comment like a C, C++, Java Languages.
PHP supports two types of comments Single line and Multiline comments, through double
slashes “ // “ for one liners comments and “/* */” for multi-line comments tags that may
extend over several lines of code.
Multiline Comment
<?php
/* this is the
Multiline
Comment
*/
?>
In the above example we can see the multiline comment started with symbol /* and end
with symbol */.
So, the multiline comment starts with one line and can be expand to more than one line.
Echo
The simplest use of echo is to print a string as argument, for example:
echo “This will print in the user ’s browser window.”;
Or equivalently:
echo(“This will print in the user ’s browser window.”);
Both of these statements will cause the given sentence to be displayed, without displaying
the quote signs.
(Note for C programmers: Think of the HTTP connection to the user as the standard output
stream for these functions.)
You can also give multiple arguments to the unparenthesized version of echo , separated by
commas, as in:
echo “This will print in the “,“user ’s browser window.”;
The parenthesized version, however, will not accept multiple arguments:
echo (“This will produce a “,“PARSE ERROR!”);
Print
The command print is very similar to echo, with two important differences:
Unlike echo, print can accept only one argument.
Now we will see how the above PHP program works is just given below.
?>
PHP lines end with a semicolon, generally speaking:
<?php
// First line of code goes here;
// Second line of code goes here;
// Third line of code goes here;
?>
Comments can be added into your program as we just did through double slashes ( // ) for
one-liners or /* and */ for opening and closing comment tags that may extend over several
lines of code.
Constants:
You can also define value - containers called constants in PHP.
The values of constants, as their name implies, can never be changed.
Constants can be defined only once in a PHP program.
Constants differ from variables in that their names do not start with the dollar sign, but
other than that they can be named in the same way variables.
However, it ’ s good practice to use all - uppercase names for constants.
In addition, because constants don’t start with a dollar sign, you should avoid naming your
constants using any of PHP ’ s reserved words, such as statements or function names.
For example, don’t create a constant called ECHO or SETTYPE.
If you do name any constants this way, PHP will get very confused!
Constants may only contain scalar values such as Boolean, integer, float, and string (not
values such as arrays and objects), can be used from anywhere in your PHP program
without regard to variable scope, and are case - sensitive.
To define a constant, use the define( ) function, and include inside the parentheses the
name you’ve chosen for the constant, followed by the value for the constant, as shown
here:
define( “MY_CONSTANT”, “19” ); // MY_CONSTANT always has the string value “ 19 ”
echo MY_CONSTANT; // Displays “ 19 ” (note this is a string, not an integer)
Constants are useful for any situation where you want to make sure a value does not
change throughout the running of your script.
Common uses for constants include configuration files and storing text to display to the
user.
Variables:
Unlike constants, variables are obviously meant to be variable—they are meant to change
or be changed at some point in your program.
A variable is simply a container that holds a certain value.
Variables get their name because that certain value can change throughout the execution of
the script.
It’s this ability to contain changing values that make variables so useful.
Example, consider the following simple PHP script:
echo 2 + 2;
As you might imagine, this code outputs the number 4 when it ’ s run.
Example:
<?php
$a=10;
$b=20;
echo $a+$b;
?>
You can set the variables $a and $b to any two values you want, either at some other place
in your code, or as a result of input from the user.
Then, when you run the preceding line of code, the script outputs the sum of those two
values.
Run the script with different values for $a and $b , and you get a different result.
Naming Variables
A variable consists of two parts:
The variable’s name
The variable’s value.
Because you’ll be using variables in your code frequently, it’s best to give your variables
names you can understand and remember.
Like other programming languages, PHP has certain rules you must follow when naming
your variables:
Variable names begin with a dollar sign ( $ ).
The first character after the dollar sign must be a letter or an underscore
Creating Variables
Creating a variable in PHP is known as declaring it.
Declaring a variable is as simple as using its name in your script:
$a;
When PHP first sees a variable’s name in a script, it automatically creates the variable at
that point.
Example of declaring and initializing a variable:
$a = 3;
This creates the variable called $a , and uses the = operator to assign it a value of 3.
<?php
$a=10;
$b=20;
echo $a+$b;
?>
Global variable
Although the concept of variable scope is extremely useful, occasionally you do actually
want to create a variable that can be accessed anywhere in your script, whether inside or
outside a function. Such a variable is called a global variable.
PHP supports global variables, but if you’re used to other programming languages you’ll find
PHP handles global slightly differently.
In PHP, all variables created outside a function are, in a sense, global in that they can be
accessed by any other code in the script that ’ s not inside a function.
To use such a variable inside a function, write the word global followed by the variable
name inside the function’s code block.
Example:
<?php
$myGlobal = "RAHUL PATEL";
function hello()
{
global $myGlobal;
echo "$myGlobal";
}
hello(); // Displays “RAHUL PATEL” ?>
You can see that the hello() function accesses the $myGlobal variable by declaring it to be
global using the global statement.
The function can then use the variable to display the greeting.
In fact, you don’t need to have created a variable outside a function to use it as a global
variable.
Take a look at the following script:
<?php
function setup()
{
PHP & My SQL Page 8
global $myGlobal;
$myGlobal = "Hello there!";
}
function hello()
{
global $myGlobal;
echo "$myGlobal";
}
setup();
hello(); // Displays “Hello there!”
?>
Finally, you can also access global variables using the $GLOBALS array.
This array is a special type of variable called a superglobal , which means you can access it
from anywhere without using the global statement.
It contains a list of all global variables, with the variable names stored in its keys and the
variable’s values stored in its values. Here’s an example that uses $GLOBALS :
<?php
$myGlobal = "Hello";
function hello()
{
echo $GLOBALS["myGlobal"];
}
hello(); // Displays “Hello there!”
?>
The hello() function accesses the contents of the $myGlobal variable via the $GLOBALS
array.
Notice that the function doesn’t have to declare the $myGlobal variable as global in order
to access its value.
Static variable
As you’ve seen, variables that are local to a function don ’ t exist outside the function.
In fact, all variables declared within a function are deleted when the function exits, and
created a new when the function is next called.
This is usually what you want to happen, because it allows you to write nicely self –
contained functions that work independently of each other.
If-else
Syntax:
if (condition)
{
statement-1
}
Or with an optional else branch:
if (condition)
{
statement-1
}
else
{
statement-2
}
When an if statement is processed, the test expression is evaluated, and the result is
interpreted as a Boolean value.
If condition is true, statement-1 is executed. If condition is not true, and there is an else
clause, statement-2 is executed.
If condition is false, and there is no else clause, execution simply proceeds with the next
statement after the if construct.
Note that a statement in this syntax can be a single statement that ends with a semicolon, a
brace-enclosed block of statements.
Conditionals can be nested inside each other to arbitrary depth.
Also, the Boolean expression can be a genuine Boolean (TRUE, FALSE, or the result of a
Boolean operator or function), or it can be a value of another type interpreted as a Boolean.
Example:-1 (Simple If)
<?php
$a=10;
if ($a == 10)
{
echo $a;
}
?>
Example:-3 (Elseif)
<?php
$a=2;
if ($a == 1)
{
print "Mon";
}
elseif($a==2)
{
print "Thu";
}
else
{
print "wrong choice";
}
?>
Switch
For a specific kind of multi way branching, the switch construct can be useful.
Rather than branch on arbitrary logical expressions, switch takes different paths according
to the value of a single expression.
The syntax is as follows, with the optional parts enclosed in square brackets ([])
switch(expression)
{
case value-1:
statement-1
statement-2
...
[break;]
case value-2:
statement-3
statement-4
...
[break;]
.....
……
[default:
default-statement]
}
The expression can be a variable or any other kind of expression, as long as it evaluates to a
simple value (that is, an integer, a double, or a string).
The construct executes by evaluating the expression and then testing the result for equality
against each case value.
As soon as a matching value is found, subsequent statements are executed in sequence
until the special statement (break ;) or until the end of the switch construct.
A special default tag can be used at the end, which will match the expression if no other
case has matched it so far.
Example:
<?php
$a=6;
switch($a)
{
case 1:
print "Mon";
break;
case 2:
print "Tue";
break;
Looping
Bounded loops versus unbounded loops
A bounded loop executes a fixed number of times—you can tell by looking at the code how
many times the loop will iterate, and the language guarantees that it won’t loop more times
than that.
An unbounded loop repeats until some condition becomes true (or false), and that
condition is dependent on the action of the code within the loop.
bounded loops—while, do-while, and for are all unbounded constructs—but as we will see
in this section, an unbounded loop can do anything a bounded loop can do.
While
The simplest PHP looping construct is while, which has the following syntax:
while (condition)
{
Statement
}
The while loop evaluates the condition expression as a Boolean—if it is true, it executes
statement and then starts again by evaluating condition.
If the condition is false, the while loop terminates. Of course, just as with if, statemen t may
be a single statement or it may be a brace-enclosed block.
Example:-
<?php
$a=1;
while ($a <= 10)
{
print "count is $a<BR>";
$a = $a + 1;
}
?>
For
The most complicated looping construct is for, which has the following syntax:
for (initial-expression;termination-check;loop-end-expression
{
Number of statements
}
In executing a for statement, first the initial-expression is evaluated just once, usually to
initialize variables.
Then termination-check is evaluated—if it is false, the for statement concludes, and if it is
true, the statement executes.
Finally, the loop-end-expression is executed and the cycle begins again with termination-
check.
As always, by statement we mean a single (semicolon-terminated) statement, a brace-
enclosed block, or a conditional construct.
Example:-
<?php
for ($i = 1; $i <= 5; $i++)
{
echo $i;
}
?>
PHP Operators
The values and variables that are used with an operator are known as operands.
Operator Types
Operators in PHP can be grouped into ten types, as follows:
Assignment Operators
You’ve already seen how the basic assignment operator ( = ) can be used to assign a value
to a variable:
$a = 8.23;
It’s also worth noting that the preceding expression evaluates to the value of the
assignment: 8.23.
This is because the assignment operator, like most operators in PHP, produces a value as
well as carrying out the assignment operation. This means that you can write code such as:
$c =$a = 8.23;
which means: “ Assign the value 8.23 to $a , then assign the result of that expression ( 8.23 )
to $c . ”
So both $a and $c now contain the value 8.23 .
The equals sign ( = ) can be combined with other operators to give you a combined
assignment operator that makes it easier to write certain expressions.
The combined assignment operators (such as +=, – =, and so on) simply give you a
shorthand method for performing typical arithmetic operations, so that you don ’ t have to
write out the variable name multiple times.
For example, you can write:
$a += $b;
rather than:
$a = $a + $b;
Comparison Operators
As you might imagine from the name, comparison operators let you compare one operand
with the other in various ways.
If the comparison test is successful, the expression evaluates to true; otherwise, it evaluates
to false.
You often use comparison operators with decision and looping statements such as if and
while.
Here’s a list of the comparison operators in PHP:
Logical Operators
PHP features six logical operators, and they all work in combination with true or false
Boolean values to produce a result of either true or false;
The main use of logical operators and Boolean logic is when making decisions and creating
loops, You’re probably wondering why the “and” and “or” operators can also be written as
& & and || .
The reason is that “and” and “or” have a different precedence to & & and || .
Operator precedence is explained in a moment.
String Operators
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 onto the left -
hand one to make a longer string.
For example:
echo “Rahul” . “patel”; // Displays “ Rahul Patel”
You can also concatenate more than two strings at once.
When PHP faces an error in the code, it outputs a verbose error message to help in finding
the cause of the error an fixing it.
Sometimes the error is wanted to be not reported, even if it occurs.
Example:-
<?php
$x = 100;
$y = 0;
@$z = $x/$y;
?>
In the above example you can see that @ operator is used in front of the $z variable so
here, error should be display that division by zero is not possible but here, we have used @
so the error will be not reported in result.
Dividing by zero should return an error, but when @ is used, no error will be reported.
Syntax errors are not caught by sing @, so they will still be reported even with using @.
Arrays:
An array is a single variable that can hold more than one value at once.
You can think of an array as a list of values.
Each value within an array is called an element, and each element is referenced by its own
index, which is unique to that array.
To access an element’s value — whether you’re creating, reading, writing, or deleting the
element — you use that element’s index.
Many modern programming languages — including PHP — support two types of arrays:
Indexed arrays
These are arrays where each element is referenced by a numeric index, usually
starting from zero.
For example, the first element has an index of 0. the second has an index of 1, and
so on
Associative arrays
This type of array is also referred to as a hash or map.
With associative arrays, each element is referenced by a string index.
For example, you might create an array element representing a customer’s age and
give it an index of “age”.
Although PHP lets you create and manipulate both indexed and associative arrays, all PHP
arrays are in fact of the same type behind the scenes.
Creating Arrays
This takes a list of values and creates an array containing those values, which you can then
assign to a variable:
$a = array( “Rahul”, “ravi”, “ajit”, “pratik” );
In this line of code, an array of four elements is created, with each element containing a
string value.
The array is then assigned to the variable $authors. You can now access any of the array
elements via the single variable name, $a , as you see in a moment.
This array is an indexed array, which means that each of the array elements is accessed via
its own numeric index, starting at zero.
In this case, the “Rahul” element has an index of 0 , “ravi” has an index of 1 , “ajit” has an
index of 2 , and “pratik” has an index of 3 .
$a*4+ = “Ajay”;
The following example code creates an indexed array and an associative array, then
displays both arrays
<?php
$a = array( "Rahul", "ravi", "ajit", "pratik" );
print_r ( $a );
?>
Multidimensional Arrays:
The ability of arrays to store other arrays in their elements allows creating multidimensional
arrays (also known as nested arrays because they comprise one or more arrays nested
inside another).
An array that contains other arrays is a two - dimensional array.
If those arrays also contain arrays, then the top - level array is a three - dimensional array,
and so on.
Creating a Multidimensional Array
<?php
$myBooks = array(
array(
"title" => "php",
"author" => "rahul",
"pubYear" => 2012
),
array(
"title" => "net",
"author" => "anil",
"pubYear" => 2012
),
PHP & My SQL Page 23
array(
"title" => "c++",
"author" => "ravi",
"pubYear" => 2012
),
array(
"title" => "cmp",
"author" => "pratik",
"pubYear" => 2012
),
);
?>
As you can see, this script creates an indexed array, $myBooks , that contains four
elements with the keys 0 , 1 , 2 , and 3 .
Each element is, in turn, an associative array that contains three elements with keys of
“title”, “author”, and “pubYear”.
foreach Constructs:
There exists a foreach Constructs (command) that will apply a set of statements for each
value in an array.
It works only on arrays, however, and will give you a big old error if you try to use it with
another type of variable.
Your syntax for the foreach command looks like this:
foreach ($array_variable as $value_variable)
{
// .. do something with the value in $value_variable
}
Example:
<html>
<head>
<title>
For Each Constructs
</title>
</head>
<body>
<?php
$a[] = "Rahul";
$a[] = "Ravi";
$a[] = "Pratik";
echo "My Name -->".'</br>';
foreach ($a as $b)
{
//these lines will execute as long as there is a value in $a
echo $b.'</br>';
}
?>
</body>
</html>
Just as with variable names, the name of the function must be made up of letters, numbers,
and underscores, and it must not start with a number.
Unlike variable names, function names are converted to lowercase before they are stored
internally by PHP, so a function is the same regardless of capitalization.
Example:-1
<?php
function add($a, $b)
{
$c=$a+$b;
echo "Total-->".$c;
}
$x = 10;
$y = 20;
add($x,$y);
?>
Argument Function
In PHP we can pass argument to the function by two way Call By Value and Call By Reference.
Call-by-Value
The default behavior for user-defined functions in PHP is call-by-value.
This means that when you pass variables to a function call, PHP makes copies of the variable
values to pass on to the function.
So, whatever the function does, it is not able to change the actual variables that appear in
the function call. This behavior can be good or bad. It’s a nice reassurance if you only want
to use a function for its returned value, but it can also be a source of confusion and
frustration if changing the passed variable is actually your goal.
Example:-
<?php
function display($b1,$b2)
{
$b1 = 30;
$b2 = 40;
}
$a1=10;
$a2=20;
display($a1,$a2);
echo $a1;
echo $a2;
?>
Output:-
10
20
Call-by-Reference
PHP offers two different ways to have functions actually modify their arguments: in the
function definition and in the function call.
Variable Function
One of the neater tricks you can do in PHP is to use variables in place of the names of user
defined functions.
That is, rather than typing a literal function name into your code, you type a dollar-sign
variable—the function that is actually called at runtime will depend on the string that that
variable has been assigned to.
In some sense, this allows us to use functions as data.
This kind of trick will be familiar to advanced C programmers and to even beginning users of
any kind of Lisp language (for example, Scheme or Common Lisp).
Example:-
<?php
function display()
{
print ("good morning</br>");
}
display();
$x='display';
$x();
?> Variable Function
Output:
good morning
good morning
Because function names are just strings, they can also be used as arguments to functions or
be returned as a function’s result.
Return Function
Values are returned by using the optional return statement.
Any type may be returned, including arrays and objects.
This causes the function to end its execution immediately and pass control back to the line
from which it was called.
If called from within a function, the return() function immediately ends execution of the
current function, and returns its argument as the value of the function call.
PHP & My SQL Page 28
Note that since return() is a language construct and not a function, the parentheses
surrounding its arguments are not required.
It is common to leave them out, and you actually should do so as PHP has less work t o do in
this case.
If no parameter is supplied, then the parentheses must be omitted and NULL will be
returned.
Calling return() with parentheses but with no arguments will result in a parse error.
You should never use parentheses around your return variable when returning by reference,
as this will not work.
You can only return variables by reference, not the result of a statement.
If you use return ($a); then you're not returning a variable, but the result of the expression
($a) (which is, of course, the value of $a).
Example:-
<?php
function sum($a,$b)
{
$c=$a+$b;
return $c;
}
$x=10;
$y=20;
$z=sum($x,$y);
echo $z;
?>
Output :-
30
In above example there are two variables are declared $x and $y then after In $z we have
assign the function so, the value return by the function_sum will be assign to $c and finally
at last values of $z will be displayed.
Default arguments:
To define a function with default arguments, simply turn the formal parameter name into
an assignment expression.
If the actual call has fewer parameters than the definition has formal parameters, PHP will
match actual with formal until the actual parameters are exhausted and then will use the
default assignments to fill in the rest.
Example:-
<?php
function info($fname="rahul",$lname="patel")
{
echo $fname;
echo $lname.'</br>';
}
info();
info("ravi");
info("ravi","dave");
?>
Output:-
Rahulpatel
func_num_args():-
It returns the total number of arguments provided in the function call operation.
For example, if "func_num_args()" returns 1, you know that there is only 1 argument
provided by calling code.
Example:-
<?php
function myMax()
{
$max = NULL;
if (func_num_args()>0) $max = func_get_arg(0);
for ($i=1; $i<func_num_args(); $i++)
{
if ($max < func_get_arg($i)) $max = func_get_arg($i);
}
return $max;
}
print("Calling a function that uses func_num_args():"."</br>");
print(" ".myMax()."</br>");
print(" ".myMax(3)."</br>");
print(" ".myMax(3, 1, 4)."</br>");
print(" ".myMax(3, 1, 4, 1, 5, 9, 2, 6, 5)."</br>");
?>
func_get_args():-
it creates and returns an array which contains values of all arguments provided in the
function call operation.
For example, if "$args = func_get_args()" is used in a function, $args will be array
containing all arguments.
Example:-
<?php
function myMin()
{
$list = func_get_args();
$min = NULL;
if (count($list)>0) $min = $list[0];
for ($i=1; $i<count($list); $i++)
{
if ($min > $list[$i]) $min = $list[$i];
}
return $min;
}