Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

ch-2 PHP

Download as pdf or txt
Download as pdf or txt
You are on page 1of 33

2.

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.

PHP & My SQL Page 1


 Single Line comment
<?php
// this is the single line comment
?>
In above example we can see the single line comment started with symbol //.
If you have a single line comment, another option is to use a # sign. Here is an example
of this:
<?php
#this is a single line comment
?>

 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 and print


 The two most basic constructs for printing to output are echo and print .
 Their language status is somewhat confusing, because they are basic constructs of the PHP
language, rather than being functions.
 As a result, they can be used either with parentheses or without them. (Function calls always
have the name of the function first, followed by a parenthesized list of the arguments to the
function.)

 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.

PHP & My SQL Page 2


Unlike echo, print returns a value, which represents whether the print statement
succeeded.
 The value returned by print will be 1 if the printing was successful and 0 if unsuccessful.
 Both echo and print are usually used with string arguments, but PHP’s type flexibility means
that you can throw pretty much any type of argument at them without causing an error.
 For example, the following two lines will print exactly the same thing:
print(“3.14159 ”); //print a string
print(3.14159); //print a number
 Technically, what is happening in the second line is that, because print expects a string
argument, the floating-point version of the number is converted to a string value before print
gets hold of it. However, the effect is that both print and echo will reliably print out numbers as
well as string arguments.

 Creating the PHP Pages:


 In order to create the PHP page follow the following steps
 Step:-1
 Enter the following program in your favorite text editor (Notepad, WordPad, or whatever),
and save it as first.php.
 Make sure you save it in a “plain text” format to avoid parsing problems, and double-check
to ensure that the file is not saved as firstprog.php.txt by default.
<html>
<head>
<title>
My First PHP Page
</title>
</head>
<body>
<?php
echo "Rahul Patel";
?>
</body>
</html>
 Step:-2
 Open this program using your browser.
 Your resulting screen should look like the one in following figure.

 Now we will see how the above PHP program works is just given below.

PHP & My SQL Page 3


 When a browser calls a PHP program, it first searches through the entire code line by line to
locate all PHP sections (those encased in the appropriate tags) and it then processes them
one at a time.
 To the server, all PHP code is treated as one line, which is why your two lines of code were
shown as one continuous line on the screen.

 Rules of PHP Syntax:


 One of the benefits of using PHP is that it is relatively simple and straightforward.
 As with any computer language, there is usually more than one way to perform the same
function.
 Once you feel comfortable writing some PHP programs, you can research shortcuts to make
yourself and your code more efficient. For the sake of simplicity, we cover only the most
common uses, rules, and functions of PHP.
 You should always keep in mind these two basic rules of PHP:
 PHP is denoted in the page with opening and closing tags as follows:
<?php

?>
 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.

 Integrating HTML with PHP:


 You will be better able to see how easily we can use HTML in the PHP program with the
following practical
 Example:
<html>
<head>
<title>
My First PHP Page
</title>
</head>
<body>
<?php
echo "<h1> I'm Rahul Patel </h1>";
echo "<h2> And i'm fine </h2>";
?>
</body>
</html>
 You can see that by inserting some HTML code within the PHP section of the program, you
accomplish two things:
 You can improve the look of your site.

PHP & My SQL Page 4


 You can keep PHP lines of code together without having to jump back and forth between
HTML and PHP.
 If you view the source of your HTML code you will see the HTML code you inserted using the
echo function displayed just as you intended.
 Some of the basic rules must be follow when we integrating HTML with PHP the basic rules are
as follow
 You’ll have to check for double quotes.
 As you may have noted when you worked through the previous example, using the echo
function involves the use of double quotation marks.
 Because HTML also uses double quotes, you can do one of two things to avoid problems:
 Use single quotes inside your HTML.
 Escape your HTML double quotes with a backslash, as in the following:
echo “He was about 6’5\” tall.”;
 Remember that you still have to follow PHP rules, even though you’re coding in HTML.
 Sometimes when you begin to code in HTML within your PHP section, you can temporarily
forget that you need to follow PHP guidelines and end your sentences with a semicolon, as well
as closing all quotes at the end of your echo statements.
 Don’t try to cram (To force, press, or squeeze) too much HTML into your PHP sections.
 If you find yourself in the middle of a PHP portion of your program, and your HTML is becoming
increasingly complex or Lengthy, consider ending the PHP section and coding strictly in HTML.

 Constants, Variables: static and global variable

 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.

PHP & My SQL Page 5


 Example:-
<?php
define("FAVNUM", "7");
echo "My favorite num is " .'</br>';
echo FAVNUM;
line break
?>
 Save the above PHP code in favnum.php file and execute in your browser by
http://localhost/favnum.php
 The output in browser will be like below:
My favorite number is
7
 We now see how it works, By defining the constant known as FAVNUM, you have set the
value as “7” which can be recalled and displayed later on.
 While this constant can’t be changed or reset throughout your program, it is available for
use by any part of your program.

 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

PHP & My SQL Page 6


The remaining characters in the name may be letters, numbers, or underscores without
a fixed limit
 Variable names are case - sensitive ( $Variable and $variable are two distinct variables), so it
’ s worth sticking to one variable naming method — for example, always using lowercase —
to avoid mistakes.
 It’s also worth pointing out that variable names longer than 30 characters are somewhat
impractical.
 Here are some examples of PHP variable names:
$my_first_variable
$anotherVariable
$x
$_123

 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;
?>

 Understanding Data Types


 All data stored in PHP variables fall into one of eight basic categories, known as data types.
 A variable’s data type determines what operations can be carried out on the variable’s data,
as well as the amount of memory needed to hold the data.
 PHP supports four scalar data types.
 Scalar data means data that contains only a single value. Here’s a list of them, including
 Example:

Scalar Data Type Description Example


Integer A whole number 15
Float A floating - point number 8.23
String A series of characters “Hello, world!”
Boolean Represents either true or false true
 As well as the four scalar types
 PHP supports two compound types.
Compound data is data that can contain more than one value. The following table
describes PHP’s compound types:

Compound Data Type Description


Array An ordered map (contains names or numbers mapped to values)
Object A type that may contain properties and methods
PHP & My SQL Page 7
 Finally, PHP supports two special data types, so called because they don’t contain scalar or
compound data as such, but have a specific meaning:
Special Data Description
Type
Resource or Contains a reference to an external resource, such as a file
database
Null May only contain null as a value, meaning the variable explicitly does not contain
any value

 Example which display the age of person by using variable.


<?php
$age=26;
echo "My age is:->";
echo $age;
?>
 Save above PHP code in age.php file and run via your web browser by
http://localhost/age.php
 The output is as below:
My age is:-> 30

 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!”
?>

 In this script, the setup() function is called first.


 It declares the $myGlobal variable as global, and gives it a value.
 Then the hello() function is called.
 It too declares $myGlobal to be global, which means it can now access its value —
previously set by setup() — and display it.
 By the way, you can also declare more than one global variable at once on the same line —
just separate the variables using commas:
function myFunction()
{
global $oneGlobal, $anotherGlobal;
}

 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.

PHP & My SQL Page 9


 However, sometimes it’s useful to create a local variable that has a somewhat longer
lifespan.
 Static variables let you do just this. These types of variables are still local to a function, in
the sense that they can be accessed only within the function’s code.
 However, unlike local variables, which disappear when a function exits, static variables
remember their values from one function call to the next.
 To declare a local variable as static, all you need to do is write the word static before the
variable name, and assign an initial value to the variable:
static $var = 0;
 The first time the function is called, the variable is set to its initial value (zero in this
example).
 However, if the variable ’ s value is changed within the function, the new value is
remembered the next time the function is called.
 The value is remembered only as long as the script runs, so the next time you run the script
the variable is reinitialized.
 Example:(Local variable)
<?php
function nextNumber()
{
$counter = 0;
return ++$counter;
}
echo "I’ve counted to:".nextNumber()." <br/> ";
echo "I’ve counted to:".nextNumber()." <br/>";
echo "I’ve counted to:".nextNumber()." <br/>";
?>
 Output:
I’ve counted to: 1
I’ve counted to: 1
I’ve counted to: 1
 Each time the nextNumber() function is called, its $counter local variable is re - created and
initialized to zero.
 Then it’s incremented to 1 and its value is returned to the calling code.
 So the function always returns 1, no matter how many times it’s called.
 Example:(Static variable)
<?php
function nextNumber()
{
static $counter = 0;
return ++$counter;
}
echo "I’ve counted to:".nextNumber()." <br/> ";
echo "I’ve counted to:".nextNumber()." <br/>";
echo "I’ve counted to:".nextNumber()." <br/>";
?>
 output:
I’ve counted to: 1
I’ve counted to: 2
I’ve counted to: 3
PHP & My SQL Page 10
 You probably won’t use static variables that often, and you can often achieve the same
effect (albeit with greater risk) using global variables.

 Conditional Structure & Looping(Control Structures)


 Branching
 The two main structures for branching are if and switch.
 If is a workhorse and is usually the first conditional structure anyone learns.
 Switch is a useful alternative for certain situations where you want multiple possible
branches based on a single value and where a series of if statements would be
cumbersome.

 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:-2 (Simple If and Else)


<?php
$a=10;

PHP & My SQL Page 11


$b=4;
if ($a > $b)
{
echo "A is greater than";
}
else
{
echo "B is greater than";
}
?>

 Example:-3 (Elseif)
<?php
$a=2;
if ($a == 1)
{
print "Mon";
}
elseif($a==2)
{
print "Thu";
}
else
{
print "wrong choice";
}
?>

 Example:-4 (Nested if……else)


<?php
$a=1;
$b=2;
$c=3;
if ($a > $b)
{
if ($a > $c)
{
print "a is max";
}
else
{
print "c is max";
}
}
else
{
if ($b > $c)
{
print "b is max";

PHP & My SQL Page 12


}
else
{
print "c is max";
}
}
?>

 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;

PHP & My SQL Page 13


case 3:
print "Wen";
break;
case 4:
print "Thu";
break;
case 5:
print "Fri";
break;
case 6:
print "sat";
break;
case 7:
print "Sun";
break;
default:
print "Wrong Choice";
}
?>

 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;
}
?>

PHP & My SQL Page 14


 Do-while
 The do-while construct is similar to while, except that the test happens at the end of the
loop.
 The syntax is:
do
{
code to be executed;
}
while (condition);
 The statement is executed once, and then the expression is evaluated.
 If the expression is true, the statement is repeated until the expression becomes false.
 The only practical difference between while and do-while is that the latter will always
execute its statement at least once.
 Example:-
<?php
$a=1;
do
{
print "count is $a<BR>";
$a = $a + 1;
}
while ($a <= 10);
?>

 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 & My SQL Page 15


 Break and continue
 The standard way to get out of a looping structure is for the main test condition to become
false.
 The special commands break and continue offer an optional side exit from all the looping
constructs, including while, do-while, and for:
The break command exits the innermost loop construct that contains it.
The continue command skips to the end of the current iteration of the innermost loop
that contains it.
 Example(Break):-
<?php
$i = 0;
while ($i<100)
{
if ($i > 6)
break;
echo $i;
$i=$i+1;
}
?>
 Example(Continue):- The following code prints the number 0 to 9, except 5.
<?php
for ($i = 0; $i<10; $i++)
{
if ($i == 5)
{
continue;
}
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:

PHP & My SQL Page 16


 Arithmetic Operators
 In PHP, the arithmetic operators (plus, minus, and so on) work much as you would expect,
enabling you to write expressions as though they were simple equations.
 For example, $c = $a + $b adds $a and $b and assigns the result to $c .
 Here’s a full list of PHP’s arithmetic operators:

 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;

PHP & My SQL Page 17


 Bitwise Operators
 PHP’s bitwise operators let you work on the individual bits within integer variables.
Consider the integer value 1234.
 For a 16 - bit integer, this value is stored as two bytes: 4 (the most significant byte) and 210
(the least significant). 4 * 256 + 210 = 1234.
 Here’s how those two bytes look as a string of bits:
 00000100 11010010
 A bit with a value of 1 is said to be set, whereas a bit with a value of 0 is unset (or not set).
 PHP’s bitwise operators let you manipulate these bits directly, as shown in the following
table.
 Each example includes both decimal values and their binary equivalents, so you can see
how the bits are altered:

 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:

PHP & My SQL Page 18


 The following examples show comparison operators in action:
<?php
$x = 23;
echo $x < 24 ."<br/>"; // Displays 1 (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/>"; // Displays “” (false) because
// $x and “23” are not the same data type
echo ( $x >= 23 ) .'<br/>'; // Displays 1 (true)
echo ( $x >= 24 ) .'<br/>'; // Displays “” (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


 Oftentimes it’s useful to add or subtract the value 1 (one) over and over.
 This situation occurs so frequently — for example, when creating loops — that special
operators are used to perform this task: the increment and decrement operators.
 They are written as two plus signs or two minus 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 from it
 The location of the operators makes a difference. Placing the operator before the variable
name causes the
 variable’s value to be incremented or decremented before the value is returned; placing the
operator after the variable name returns the current value of the variable first, then adds or
subtracts one from the variable.

PHP & My SQL Page 19


 Example:-
<?php
$a = 5;
echo ++$a; // Displays “6” (and $a now contains 6)
$b = 5;
echo $b++; // Displays “5” (and $b now contains 6)
?>

 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;

 Here are some simple examples of logical operators in action:


<?php
$x = 2;
$y = 3;
echo ( ($x > 1) && ($x < 5) ) ."</br>"; // Displays 1 (true)
echo ( ($x == 2) or ($y == 0) ) ."</br>"; // Displays 1 (true)
echo ( ($x == 2) xor ($y == 3) ) ."</br>"; // Displays “” (false) because both
// expressions are true
echo ( !($x == 5 ) ) ."</br>"; // Displays 1 (true) because
// $x does not equal 5
?>

 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.

PHP & My SQL Page 20


 Furthermore, the values you concatenate don’t have to be strings; thanks to PHP ’ s
automatic type conversion, non - string values, such as integers and floats, are converted to
strings at the time they ’ re concatenated:
 $tempF = 451;
 // Displays “ Books catch fire at 232.777777778 degrees C. ”
 echo “Books catch fire at “ . ( (5/9) * ($tempF - 32) ) . “ degrees C.”;

 Execution Operator - Executing Server Side Commands


 All of the operators we have looked at so far are similar to those available in other
programming and scripting languages.
 With the execution operator, however, we begin to experience the power of PHP as server
side scripting environment.
 The execution operator allows us to execute a command on the operating system that hosts
your web server and PHP module and then capture the output.
 You can do anything in an execution operator that you could do as if you were sitting at a
terminal window on the computer (within the confines of the user account under which
PHP is running).
 Given this fact, it should not escape your attention that there are potential security risks to
this, so this PHP feature should be used with care.
 The execution operator consists of enclosing the command to be executed in back quotes
(`).
 The following example runs the UNIX/Linux uname and id commands to display information
about the operating system and user account on which the web server and PHP module are
running (note that these command will not work if you are running a Windows based
server):
 Example:-
<?php
echo 'uname -a' . '</br>';
echo 'id';
?>

 Error control operator:

 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 @.

PHP & My SQL Page 21


 Arrays, foreach constructs

 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 .

 Accessing Array Elements:


Once you’ve created your array, how do you access the individual values inside it? In
fact, you do this in much the same way as you access the individual characters within a
string:
$a = array( “Rahul”, “ravi”, “ajit”, “pratik” );

$b = $a[0]; // $myAuthor contains “Rahul”


$c = $a[1]; // $anotherAuthor contains “ravi”

$a = array( “Rahul”, “ravi”, “ajit”, “pratik” );


$pos = 2;
echo $a[$pos + 1]; // Displays “ajit”

PHP & My SQL Page 22


 Changing Elements:
As well as accessing array values, you can also change values using the same techniques.
It’s helpful to think of an array element as if it were a variable in its own right; you can
create, read, and write its value at will.
For example, the following code changes the value of the third element in an indexed
array from “ajit” to “dipak“.
$a = array( “Rahul”, “ravi”, “ajit”, “pratik” );
$a*2+ = “dipak”;
What if you wanted to add a fifth author? You can just create a new element with an
index of 4, as follows:
$a = array( “Rahul”, “ravi”, “ajit”, “pratik” );

$a*4+ = “Ajay”;

 Outputting an Entire Array with print_r()


You can’t just print an array with print() or echo() , like you can with regular variables,
because these functions can work with only one value at a time.
However, PHP does give you a function called print_r() that you can use to output the
contents of an array for debugging.
Using print_r() is easy — just pass it the array you want to output:
print_r( $a);

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”.

 Accessing Elements of Multidimensional Arrays:


Using the square bracket syntax that you’ve already learned, you can access any
element within a multidimensional array.
Here are some examples (these work on the $myBooks array just shown):
print_r( $myBooks[2] );
Array ( [title] => c++ [author] => ravi [pubYear] => 2012 )

// Displays “The Only Title”


echo "<br/>" . $myBooks[1]["title"] ."<br/>";
net
The print_r() example shows that the second element of $myBooks is in fact an
associative array containing information on “ The Trial. ”
Meanwhile, the two echo() examples show how to access elements in the nested
associative arrays. As you can see, you use two keys within two sets of square brackets.
The first key is the index of an element in the top - level array, and the second key is the
index of an element in the nested array. In this example, the first key selects the
associative array you want to access, and the second key selects an element within that
associative array.

 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
}

foreach ($array_variable as $key_var => $value_var)


{
PHP & My SQL Page 24
// .. do something with $key_var and/or $value_var
}

 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>

 Defining Your Own Functions


 Functions are most useful when you will be using the code in more than one place, but they can
be helpful even in one-use situations, because they can make your code much more readable.
 Syntax
 Function definitions have the following form:
function function-name ($argument-1, $argument-2, ..)
{
statement-1;
statement-2;
...
}

 That is, function definitions have four parts:


The special word function
The name that you want to give your function
The function’s parameter list—dollar-sign variables separated by commas
The function body—a brace-enclosed set of statements

 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.

PHP & My SQL Page 25


 The short version of what happens when a user-defined function is called is:
 PHP looks up the function by its name (you will get an error if the function has not yet been
defined).
 PHP substitutes the values of the calling arguments (or the actual parameters) into the
variables in the definition’s parameter list (or the formal parameters).
 The statements in the body of the function are executed. If any of the executed statements
are return statements, the function stops and returns the given value. Otherwise, the
function completes after the last statement is executed, without returning a value.

 Example:-1
<?php
function add($a, $b)
{
$c=$a+$b;
echo "Total-->".$c;
}
$x = 10;
$y = 20;
add($x,$y);
?>

 Example:-2 (Return A value)


<?php
function add($a, $b)
{
return $a+$b;
}
$x = 10;
$y = 20;
$c=add($x,$y);
echo "Total-->".$c;
?>

 Formal parameters versus actual parameters:


 In the preceding examples, the arguments we passed to our functions happened to be
variables, but this is not a requirement.
 The actual parameters (that is, the arguments in the function call) may be any expression
that evaluates to a value.
 In our examples, we could have passed numbers to our function calls rather than variables,
as in:
 add(10,20);
 Also, notice that in the examples we had a couple of cases where the actual parameter
variable had the same name as the formal parameter (for example, $a), and we also had
cases where the actual and formal names were different. ($x is not the same as $a.)
 As we will see in the next section, this name agreement doesn’t matter either way—the
names of a function’s formal parameters are completely independent of the world outside
the function, including the function call itself.

PHP & My SQL Page 26


 Example:-
<?php
function add($a,$b)
{
$c=$a+$b;
echo "Addition-->".$c.'</br>';
}
function sub($d,$e)
{
$f=$d-$e;
echo "Sub-->".$f;
}
add(10,20); Actual parameters
$x=20;
$y=10;
sub($x,$y); Formal parameters
?>

 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.

PHP & My SQL Page 27


 Example:-
<?php
function display(&$b1,&$b2)
{
$b1 = 30;
$b2 = 40;
}
$a1=10;
$a2=20;
display($a1,$a2);
echo $a1;
echo $a2;
?>
 Output:-
30
40

 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

PHP & My SQL Page 29


Ravipatel
Ravidave
 The main limitation of default arguments is that the matching of actual to formal
parameters is determined by the ordering of both—it’s first-come, first-served.

 Variable length argument


 func_get_arg(position):-
It returns the value of the specified argument provided in the function call operation.
"position" is the position index of the specified argument.
The position index of the first argument is 0.
For example, if "func_get_arg(2)" is used in a function, it will return the value of the 3rd
argument.
Example:-
<?php
function f2c($fahrenheit)
{
$celsius = (func_get_arg(0) - 32.0) / 1.8;
return $celsius;
}
print("Calling a function that uses func_get_arg():</br>");
if (f2c(20.0)<0.0) print(" It's cold here!\n");
?>
output:-
It's cold here!

 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>");
?>

PHP & My SQL Page 30


Output:-
Calling a function that uses func_num_args():
3
4
9

 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;
}

print("Calling a function that uses func_get_args():</br>");


print(" ".myMin()."</br>");
print(" ".myMin(5)."</br>");
print(" ".myMin(5, 6, 2)."</br>");
print(" ".myMin(5, 6, 2, 9, 5, 1, 4, 1, 3)."</br>");
?>
Output:-
Calling a function that uses func_get_args():
5
2
1
 With all these 3 functions, we say that PHP supports variable-length argument lists with
some basic rules:
The function call can provide more arguments than the number of argument variables
defined in the function statement.
 You can pass arguments to a function that has no argument variable defined.

PHP & My SQL Page 31


 PHP Control Structures:
Name Syntax Behavior
If(or if-else) if (test)statement-1 Evaluate test and if it is true,
-or- execute statement-1. If test is false
if (test) and there is an else clause,
statement-1 execute statement-2. The elseif
else construct is a syntactic shortcut for
statement-2 else clauses, where the included
-or- statement is itself an if construct.
if (test)
statement-1 Statements may be single
elseif (test2) statements terminated with a
statement-2 semicolon or brace-enclosed
else blocks.
statement-3

Name Syntax Behavior


Ternary operator expression-1 ? Evaluate expression-1 and
expression-2 : interpret it as a Boolean. If it is
expression-3 true, evaluate expression-2 and
return it as the value of the entire
expression. Otherwise, evaluate
and return expression-3.

Switch switch(expression) Evaluate expression, and compare


{ its value to the value in each case
case value-1: clause. When a matching case is
statement-1 found, begin executing statements
statement-2 in sequence (including those from
... later cases), until the end of the
[break;] switch statement or until a
case value-2: break statement is encountered.
statement-3 The optional default case will
statement-4 execute if no other case has
... matched the expression.
[break;]
...
[default:
default-statement]
}

While while (condition) Evaluate condition and interpret it


statement as Boolean. If condition is false, the
while construct terminates. If it
is true, execute statement, and
keep executing it until condition
becomes false. Terminate the
while loop if the special break
command is encountered, and skip
the rest of the current iteration if
continue is encountered.

Do-while do statement Perform statement once


while (condition); unconditionally; then keep
repeating statement until
condition becomes false. (The
break and continue
commands are handled as in
while.)
PHP & My SQL Page 32
For for (initial-expression; Evaluate initial-expression once
termination-check; unconditionally. Then if
loop-end-expression) termination-check is true, evaluate
statement statement, and then loop-endexpression,
and repeat that loop
until termination-check becomes
false. Clauses may be omitted, or
multiple clauses of the same kind
can be separated with commas—
a missing termination-check is
treated as true. (The break and
continue commands are
handled as in while.)

Exit (or die) exit(message-string or Terminate script immediately,


return-value), or without further parsing. The
equivalently die() construct is an alias for
die(message-string or exit().
return-value)

PHP & My SQL Page 33

You might also like