0% found this document useful (0 votes)
38 views144 pages

PHP Unit I Full

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
38 views144 pages

PHP Unit I Full

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 144

PHP

UNIT-1
PHP OVERVIEW
• PHP - Hypertext Preprocessor
• Developed by Rasmus Lerdorf in 1994
• PHP is a widely-used, open source scripting language
• PHP scripts are executed on the server
• PHP is free to download and use
• PHP files can contain text, HTML, CSS, JavaScript, and PHP code
• PHP code is executed on the server, and the result is returned to the
browser as plain HTML
• PHP files have extension ".php"
• PHP is a server scripting language, and a powerful tool for making
dynamic and interactive Web pages.
• PHP is a widely-used, free, and efficient alternative to competitors
such as Microsoft's ASP.
• PHP 7 is the latest stable release.
• Functions:
• PHP can generate dynamic page content
• PHP can create, open, read, write, delete, and close files on the server
• PHP can collect form data
• PHP can send and receive cookies
• PHP can add, delete, modify data in your database
• PHP can be used to control user-access
• PHP can encrypt data
• PHP runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.)
• PHP is compatible with almost all servers used today (Apache, IIS,
etc.)
• PHP supports a wide range of databases.
• PHP is free. Download it from the official PHP resource: www.php.net
• PHP is easy to learn and runs efficiently on the server side.

Instead of lots of commands to output HTML (as seen
in C or Perl), PHP pages contain HTML with embedded
code that does "something" (like in the next slide, it
outputs "Hi, I'm a PHP script!").


The PHP code is enclosed in special start and end
processing instructions <?php and ?> that allow you to
jump into and out of "PHP mode."
It renders as HTML that looks like this:


PHP code is executed on the server, generating HTML
which is then sent to the client.


The client would receive the results of running that
script, but would not know what the underlying code
was.
PHP Introduction
•On windows, you can download and install WAMP. With one
installation and you get an Apache webserver, database server and php.
•http://www.wampserver.com

•On mac, you can download and install MAMP.


•http://www.mamp.info/en/index.html
INCORPORATING PHP WITHIN HTML
• When a web server encounters the extension .php in a requested file,
it automatically passes it to the PHP processor.
• To trigger the PHP commands, the following new tag is used
• <?php
• The entire sections of PHP can be placed inside this tag, and they
finish only when the closing part is encountered like:
• ?>
• Example: Alternative syntax: (Not encouraged)
• <?php <?
• echo “Hello World”; echo “Hello World”;
• ?> ?>
• The alternative syntax is deprecated so no longer used.

• Refer the examples:


• http://lpmj.net
THE STRUCTURE OF PHP
• Comments:
• Two ways:
• 1. A single line into a comment by preceding it with a pair of forward
slashes
• // Palindrome program
• 2. Use the comment directly after a line of code to describe its action
like:
• $x+=10; // Increment $x by 10
• Multiline comment:
• <?php
• /* This is an example of
• multiline comments which
• will not be interpreted*/
• The user can use /* and */ pairs of characters to open and close
comments almost anywhere you like inside your code.
BASIC SYNTAX
• PHP has roots in C and Perl, but looks like java.
• Semicolons:
• $x+=10;
• If semicolon is missed, PHP will treat multiple statements like one
statement.
• The $ symbol:
• We should place $ in front of all variables to make the PHP parser
faster.
• Ex:
• <?php
• $mycounter =1;
• $mystring = “Hello”;
• $myarray = array(“one”, ”two”, “three”);
• ?>
VARIABLES
• String Variables:
• $username = “Fred Smith”;
• To display the string,
• echo $username;
• We can assign it to another variable,
• $current_user=$username;
• Example Program:
• <?php //test.php
• $username = “fred smith”;
• echo $username;
• Echo “<br>”;
• $current_user = $username;
• echo $current_user;
• The result be two occurences of name fred smith.
• Execution:
• 1.IDE
• 2.Program editor and save it to your server’s document root directory.
• 3. Call the program by entering the command into the browser’s
address bar:
• http://localhost/test.php
• http://localhost:8080/test.php
• Numeric Variables:
• $count = 18;
• $count = 17.5;
• Arrays:
• An array is a special variable, which can hold more than one value at a
time.
• $team = array(‘Bill’, ‘Mary’, ‘Mike’, ‘Chris’, ‘Anne’);
• To display the name of the fourth player,
• echo $team[3]; //display the name “chris”
• In PHP, the array() function is used to create an array;
• In PHP, there are three types of arrays:
• Indexed arrays - Arrays with a numeric index
• Associative arrays - Arrays with named keys
• Multidimensional arrays - Arrays containing one or more arrays
• Indexed Arrays:
• There are two ways to create indexed arrays:
• 1. The index can be assigned automatically (index always starts at 0),
like this:
• Ex: $cars = array("Volvo", "BMW", "Toyota");
• 2. The index can be assigned manually:
• $cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota";
• Example Program:
• <?php
$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>
• Output:
• I like Volvo, BMW and Toyota.
• Associative arrays:
• Associative arrays are arrays that use named keys that you assign to
them.
• There are two ways to create an associative array:
• 1. $age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
• 2. $age['Peter'] = "35";
$age['Ben'] = "37";
$age['Joe'] = "43";
• Example Program:
• <?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
echo "Peter is " . $age['Peter'] . " years old.";
?>
• Output:
• Peter is 35 years old
• Multidimensional Arrays:
• A multidimensional array is an array containing one or more arrays.
• PHP supports multidimensional arrays that are two, three, four, five,
or more levels deep. However, arrays more than three levels deep are
hard to manage for most people.
• $cars = array (
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);
<?php
$oxo = array(array('x', ' ', 'o'),
array('o', 'o', 'x'),
array('x', 'o', ' '));

echo $oxo[1][2];
?>
Output: x
• Third element in the second row of the array
Name Stock Sold

Volvo 22 18

BMW 15 13

Saab 5 2

Land Rover 17 15
• Program:
<?php
echo $cars[0][0].": In stock: ".$cars[0][1].", sold: ".$cars[0][2].".<br>";
echo $cars[1][0].": In stock: ".$cars[1][1].", sold: ".$cars[1][2].".<br>";
echo $cars[2][0].": In stock: ".$cars[2][1].", sold: ".$cars[2][2].".<br>";
echo $cars[3][0].": In stock: ".$cars[3][1].", sold: ".$cars[3][2].".<br>";
?>
Output:
• Volvo: In stock: 22, sold: 18.
BMW: In stock: 15, sold: 13.
Saab: In stock: 5, sold: 2.
Land Rover: In stock: 17, sold: 15.
• Variable-naming rules:
• The variable name must start with a letter of the alphabet or the _
character.
• It can contain only the characters a-z, A-Z, 0-9 and _ character.
• It may contain spaces. If variable contains more than one word, it
should be separated with the _ character (e.g.$user_name)
• It is case sensitive.
OPERATORS
• The mathematical, string, comparison and logical commands such as
plus, minus, multiply and divide.
• PHP looks like a plain arithmetic.
• Ex: echo 6 + 2;
• TYPES:
• Arithmetic Operators:
• Four operations - +,-,/, modules
Operator Description Example
+ Addition $j + 1
- Subtraction $j - 6
* Multiplication $j * 11
/ Division $j/4
% Modulus (division remainder) $j%9
++ Increment ++$j
-- Decrement --$j
• Assignment Operators
• These operators are used to assign values to variables. They start with
simple = and move on to +=, -=, and so on.
• The operator += adds the value on the right side to the variable on
the left, instead of totally replacing the value on the left.
• Ex: $count +=1; sets count to 6. (If count value starts with value 5).
• Strings have their own operator, the period (.).
Operator Example Equivalent to
= $j = 15 $j = 15
+= $j += 5 $j = $j +5
-= $j - = 3 $j = $j -3
*= $j *=8 $j = $j * 8
/= $j /= 16 $j = $j / 16
.= $j .= $k $j = $j . $k
%= $j %= 4 $j = $j %4
• Comparison Operators:
• These operators are used inside a construct such as an if statement
for comparing two items.
•= - Assignment operator
• == - Comparison operator
Operator Description Example
== is equal to $j==4
!= is not equal to $j != 21
> is greater than $j > 3
< is less than $j < 100
>= is greater than or equal to $j > = 15
<= is less than or equal to $j <= 8
• Logical Operators:
Operator Description Example
&& and $j == 3 && $k ==2
and low-precedence and $j == 3 and $k == 2
|| or $j < 5 || $j > 10
or low-precedence or $j < 5 or $j > 10
! not ! ($j == $k)
xor exclusive or $j xor $k
• xor – exclusive OR returns a true value if either value is TRUE, but a
FALSE value if both inputs are TRUE or both inputs are FALSE.
• Variable Assignment: 2 syntax:
• 1. Variable = value
• 2. Other Variable = variable
• Variable Incrementing and Decrementing:
• Adding or subtracting 1 :
• ++$x;
• - -$y;
• Ex:
• If ( ++$x ==10) echo $x; (first increment and test)
• If ($y- - ==0) echo $y;
• Result: -1
• String Concatenation:
• It uses the period (.) to append one string of characters to another.
• Ex: echo “You have” . $msgs. ”messages”;
• Output: You have 5 messages
• To append one string with another, .=, like this
• $bulletin.=$newsflash;
• String types:
• Based on the type of quotation mark that we use, two types of strings
are supported.
• 1. If we wish to assign a literal string, preserving the exact contents, we
should use the single quotation mark(‘) like,
• $info = ‘Preface variables with a $ like this: $variable’;
• In this case, every character within the single-quoted string is assigned to
$info.
• If you had used double quotes, PHP would have attempted to
evaluate $variable as a variable.
• On the other hand, when you want to include the value of a variable
inside a string, you do so by using double-quoted strings.
• Echo “This week $count people have viewed your profile”;

O/P: This week 5 people have viewed your profile
• Escaping characters:
• Sometimes, a string needs to contain characters with special meanings
that might be interpreted incorrectly.
• Ex: $text = ‘My spelling’s atroshus’; // erroneous syntax
• The second quotation mark encountered in the word spelling’s will tell
the PHP parser that the string end has been reached. Consequently, the
rest of the line will be rejected as an error.
• To correct this, add a backslash character before the offending
quotation mark:
• $text = ‘My spelling\’s still atroshus’;
• Additionally we can use escape characters to insert various special
characters into strings such as tabs (\t), newlines(n) and carriage
returns(r).
• Ex:
• $heading = “Date\tName\tPayment”;
• Note:
• These special backslash-preceded characters work only in double-
quoted stings.
• In single-quoted strings, only the escaped apostrophe (‘\’) and escaped
backslash itself(\\) are recognized as escaped characters.
• Variable Typing:
• PHP is a loosely typed language.
• This means, that variables do not have to be declared before they are
used and PHP always converts variables to the type required by their
context when they are accessed.
• Ex:
• we can create a multiple-digit number and extract the nth digit from
it simply by assuming it to be a string.
• Ex: Automatic conversion from a number to a string
• <?php
• $number = 12345 * 67898;
• echo substr ($number,3,10);.
• ?>
• The PHP function substr asks for one character to be returned from
$number, starting at the fourth position (PHP offsets start from zero).
• Ex: Automatically converting a string to a number
<?php
$pi = “ 3.1415927”;
$radius = 5;
Echo $pi * ($radius * $radius);
?>
The variable $pi is set to a string value, which is then automatically
turned into a floating-point number in the third line by the equation for
calculating a circle’s area, which outputs the value 78.5398175.
CONSTANTS
• Similar to variables, holding information to be accessed later.
• To create a constant, use the define() function.
• Syntax
• define(name, value, case-insensitive)
define(“ROOT_LOCATION”, “/usr/local/www/”, True);
• Then to read the contents of the variable, just refer like a regular
variable (not preceded by the dollar sign).
• $directory = ROOT_LOCATION;
• Note:
• Use uppercase for constant variable names.
• Predefined Constants:

_LINE_ The current number of the file


_FILE_ Full path and filename of the file. If used
inside an include, the name of the
included file is returned.
_DIR_ The directory of the file. If used inside an
include, the directory of the included file
is returned.
_FUNCTION_ The function name.
_CLASS_ The class name.
_METHOD_ The class method name.
_NAMESPACE_ The name of the current namespace.
• Ex:
• Echo “This is line “ . _LINE_. “ of file “. _FILE_;

• Output:
• The current program line in the current file (including the path) being
executed to be output to the web browser.
• This is line 5 of file x.
Difference between echo and print
commands
• Print: It is a function-like construct that takes a single parameter and
has a return value (always 1), whereas echo is purely a PHP language
construct.
• Echo cannot be used as part of more complex expression, whereas
print can.
• Ex:
• $b ? Print “TRUE” : print “FALSE”;
Functions
• It is used to separate out sections of code that perform a particular task.
• Syntax:
• function functionName() {
code to be executed;
}
• Ex:
• <?php
function writeMsg() {
echo "Hello world!";
}
writeMsg(); // call the function
?>
• PHP Function Arguments:
• Information can be passed to functions through arguments. An
argument is just like a variable.
• Arguments are specified after the function name, inside the
parentheses. You can add as many arguments as you want, just
separate them with a comma.
• <?php
function familyName($fname) {
echo "$fname Refsnes.<br>";
}
familyName("Jani");
familyName("Hege");
familyName("Stale");
familyName("Kai Jim");
familyName("Borge");
?>
• Output:
• Jani Refsnes.
Hege Refsnes.
Stale Refsnes.
Kai Jim Refsnes.
Borge Refsnes.
• <?php
function familyName($fname, $year) {
echo "$fname Refsnes. Born in $year <br>";
}

familyName("Hege", "1975");
familyName("Stale", "1978");
familyName("Kai Jim", "1983");
?>
• OUTPUT:
• Hege Refsnes. Born in 1975
Stale Refsnes. Born in 1978
Kai Jim Refsnes. Born in 1983
• Variable Scope:
• 1. Local variables
• 2. Global variables
• 3. Static variables
• 4. Superglobal variables

• Local variables:
• Variables created within and can be accessed only by a function.
• They are temporary variables that are used to store partially processed results
prior to the function’s return.
• One set of local variables is the list of arguments to a function.
• Ex:1
• <?php
• function longdate($timestamp)
• {
• $temp = date (“l F jS Y”, $timestamp); // l – day, F – month, jS-date, Y- year
• return “The date is $temp”;
• }
• ?>
• Here we have assigned the value returned by the date function to the
temporary variable $temp, which is then inserted into the string
returned by the function.
• As soon as the function returns, the value of $temp is cleared, as if it
had never been used at all.
• Ex:2
• <?php
• $temp=“The date is “; // error
• echo longdate(time());
• function longdate($timestamp)
•{
• return $temp.date(“l F jS Y”, $timestamp);
•}
• ?>
• $temp was neither created within the longdate function nor passed
to it as a parameter, longdate cannot access it.
• Therefore, this code snippet outputs only the date, not the preceding
text. In fact, it will first display the error message
• Notice: Undefined variable: temp
• Reason:
• By default, variables created within a function are local to that
function, and variables created outside of any functions can be
accessed only by non-function code.
Solutions
• EX:2 (temp as an reference)
• <?php
• $temp = “The date is “;
• echo $temp.longdate(time());
• function longdate($timestamp)
• {
• return date(“l F jS Y “, $timestamp);
• }
• ?>
• The reference to $temp is moved out of the function. The reference appears in the
same scope where the variable was defined.
• Ex:3 ($temp as an argument)
• <?php
• $temp = "The date is ";
• echo longdate($temp, time());

• function longdate($text, $timestamp)


• {
• return $text . date("l F jS Y", $timestamp);
• }
• In the above example, it passes $temp to the longdate function as an extra argument.
longdate reads it into a temporary variable that it creates called $text and outputs the
desired result.
GLOBAL VARIABLES
• When all the code need to access the variable, it should be in global
scope.
• The keyword global is used.
• Ex:
• global $is_logged_in;
• When all the code need to know whether it is interacting with a
logged-in user or a guest.
• The login function simply set that variable to 1 upon a successful login
attempt, or 0 upon its failure.
• Because the scope of the variable is global, every line of code in your
program can access it.
• The global variable should be used in caution.
• If we have too many global variables, we have the risk of using one of
those names again locally.
STATIC VARIABLES
• In case of local variables, if a function runs many times, it starts with a
fresh copy of the variable and the previous setting has no effect.
• If we have a local variable inside a function that we don’t want any
other parts of our code to have access to, but would like to keep its
value for the next time the function is called?
• For ex: if we want counter to track how many times a function is
called, the solution is to declare a static variable.
• Ex:
• <?php
• function test ( )
• {
• static $count = 0;
• echo $count;
• $count++;
• }
• ?>
• The first line of function test creates a static variable called $count
and initializes it to a value of 0.
• The next line outputs the variable’s value, the final one increments it.
• The next time the function is called, because $count has already been
declared, the first line of the function is skipped.
• Then the previously incremented value of $count is displayed before
the variable is again incremented.
• If we plan to use static variables, we should note that we cannot
assign the result of an expression in their definitions.
• They can be initialized only with the predetermined values.
• Ex: allowed and disallowed static variable declarations
• <?php
• static $int = 0 ; //allowed
• static $int = 1 + 2; //disallowed (will produce parse error)
• static $int = sqrt(144); // disallowed
• ?>
SUPERGLOBAL VARIABLES
• Starting with PHP 4.1.0, several predefined variables are available.
• These are known as superglobal variables, which means that they are
provided by the PHP environment but are global within the program
accessible absolutely everywhere.
• These superglobal contains lot of useful information about the
currently running program and its environment. They are structured
as associative arrays.
SUPERGLOBAL NAME CONTENTS
$GLOBALS All variables that are currently defined in the global
scope of the script. The variable names are the keys of
the array.
$_SERVER Information such as headers, paths, and script
locations. The entries in this array are created by the
webserver, and there is no guarantee that every web
server will provide any or all of these.
$_GET Variables passed to the current script via the HTTP Get
method
$_POST Variables passed to the current script via the HTTP
Post method
$_FILES Items uploaded to the current script via the HTTP Post
method
$_COOKIE Variables passed to the current script via HTTP
cookies.
SUPERGLOBAL NAME Contents
$_SESSION Session variables available to the current script
$_REQUEST Contents of information passed from the browser; by
defaults, $_GET,$POST, and $_COOKIE.
$_ENV Variables passed to the current script via the
environment method
• To use superglobal variables:
• To refer the user to the current web page,
• $came_from = $_SERVER[‘HTTP_REFERER’];
• If the user directly visit the browser, by just typing the URL, then
$camefrom will be set to an empty string.
SUPERGLOBALS AND SECURITY
• We should use superglobals with caution, because they are often used
by hackers trying to find exploits to break into the website.
• They load the $_POST, $_GET or other superglobals with the malicious
code, such as UNIX or MySQL commands that can damage of display
sensitive data if access them.
• Therefore we should always sanitize superglobals before using them.
• One way to do this using PHP htmlentities function.
• It converts all characters into HTML entities.
• For ex: less-than and greater-than characters are transformed into the
strings &lt; and &gt; so they are harmless.
• EX:
• $came_from = htmlentities($_SERVER[‘HTTP_REFERER’]);
EXPRESSIONS AND CONTROL FLOW
IN PHP
• EXPRESSIONS:
• It is a combination of values, variables, operators, and functions that
results in a value.
• Ex: y = 3(abs(2x) +4)
• The equivalent statement in PHP is
• $y = 3* (abs(2 * $x) + 4);
• The value returned (y, or $y) can be a number, string, or a boolean
value.
• TRUE or FALSE?
• A basic Boolean value can be either TRUE or FALSE. For ex:
• 20>9 (20 is greater than 9) is TRUE, and the expression 5 ==6(5 is
equal to 6) is FALSE.
• Ex:1 Outputting the values of TRUE and FALSE
• <?php //test.php
• echo “a: [“ . TRUE . “]<br>”;
• echo “b: [“ . FALSE. “]<br>”;
• ?>
• Output:
• a: [1]
• b: []
• Ex 2: Four simple Boolean expressions
• <?php
• echo “a: [“ . (20>9) . “]<br>”; O/P: a: [1]
• echo “b: [“ . (5 == 6) . “]<br>”; b: []
• echo “c: [“ . (1 == 0) . “]<br>”; c: []
• echo “d: [“ . (1 == 1) . “]<br>”; d: [1]
• ?>
LITERALS AND VARIABLES
• The simplest form of an expression is a literal, which simply means
something that evaluates to itself, such as the number 73 or the string
“Hello”.
• An expression could also simply be a variable, which evaluates to the
value that has been assigned to it.
• Ex:3
• <?php
• $myname = “brian”;
• $myage = 37;
• echo “a: “ . 73 . “<br>”; // Numeric literal
• echo “b: ” . “Hello” . “<br>”; // String literal
• echo “c: ” . FALSE . “<br>”; // Constant literal
• echo “d: ” . $myname . “<br>”; // String variable
• echo “e: “ . $myage . “<br>”; // Numeric variable
• ?>
• Output:
• a:73
• b: Hello
• c:
• d: brian
• e: 37
• When we combine assignment or control flow constructs with expressions,
the result is a statement.
• Ex: 4
• <?php
• $days_to_new_year = 366 - $day_number; // expression
• If ($days_to_new_year < 30)
•{
• Echo “Not long now till new year”; //statement
•}
• ?>
OPERATORS
• PHP offers a lot of powerful operators that range from arithmetic,
string, and logical operators to assignment, comparison and more….
• Each operator takes a different number of operands:
• Unary operators, such as incrementing ($a++) or negation (-$a), which
take a single operand.
• Binary operators, which represent the bulk of PHP operators,
including addition, subtraction, multiplication and division.
• One ternary operator, which takes the form ? x : y.
Operator Description Example
Arithmetic Basic mathematics $a + $b
Array Array Union $a + $b
Assignment Assign values $a = $b + 23
Bitwise Manipulate bits within bytes 12 ^ 9
Comparison Compare two values $a < $b
Execution Execute contents of back ticks ‘ls –al’
Increment / decrement Add or subtract 1 $a++
Logical Boolean $a and $b
String Concatenation $a . $b
• Operator Precedence:
Operator (s) Type
() Parentheses
++ -- Increment / decrement
! Logical
*/% Arithmetic
+-. Arithmetic and string
<< >> Bitwise
< <= > >= <> Comparison
== != === !== Comparison
Operator(s) Type
& Bitwise (and references)
^ Bitwise
| Bitwise
&& Logical
|| Logical
?: Ternary
= += -= *= /= .= %= &= != ^= <<= >>= Assignment
and Logical
xor Logical
or Logical
ASSOCIATIVITY
• The direction of processing is called the operator’s associativity, for
some operators, there is no associativity.
• Operator Description Associativity
CLONE NEW Create a new object None
< <= >= == != === !== <> Comparison None
! Logical NOT Right
~ Bitwise NOT Right
++ -- Increment and decrement Right
(int) Cast to an Integer Right
(double) (float) (real) Cast to a floating-point Right
number
Operator Description Associativity
(string) Cast to a string Right
(array) Cast to an array Right
(object) Cast to an object Right
@ Inhibit error reporting Right
= += -= *= /= Assignment Right
.= %= &= |= ^= <<= >>= Assignment Right
+ Addition and unary plus Left
- Subtraction and negation Left
* Multiplication Left
/ Division Left
% Modulus Left
. String concatenation Left
• Ex: Multiple assignment statement
• <?php
• $level = $score = $time = 0;
• ?>
• This multiple assignment is possible only if the rightmost part of the
expression is evaluated first and then processing continues in a right-
to-left direction.
RELATIONAL OPERATORS
• It test two operands and return a Boolean result of either TRUE or
FALSE. There are three types of relational operators: equality,
comparison, and logical.
• EQUALITY:
• The equality operator is == (two equals signs) not to be confused with
= (single equals sign) assignment operator.
• <?php
• $month= “March”; // assigns a value
• if ( $month == “March”) echo “It’s springtime”; // test for equality
• ?>
• PHP is loosely typed language, so where it will convert them to
whatever type makes the best sense of it.
• <?php
• $a = "1000";
• $b = "+1000";
• if ($a == $b) echo "1"; // 1
• if ($a === $b) echo "2"; // no output
• ?>
• However, if you run the example, you will see that it outputs the
number 1, which means that the first if statement evaluated to TRUE.
• This is because both strings were first converted to numbers, and
1000 is the same numerical value as +1000.
• In contrast, the second if statement uses the identity operator—three
equals signs in a row—which prevents PHP from automatically
converting types.
• $a and $b are therefore compared as strings and are found to be
different, so nothing is output.
• In the same way that you can use the equality operator to test for
operands being equal, you can test for them not being equal using !=,
the inequality operator.
• In the following example, the equality and identity operators have
been replaced with their inverses.
• <?php
• $a = "1000";
• $b = "+1000";
• if ($a != $b) echo "1";
• if ($a !== $b) echo "2";
• ?>
• And, as you might expect, the first if statement does not output the
number 1, because the code is asking whether $a and $b are not
equal to each other numerically.
• Instead, it outputs the number 2, because the second if statement is
asking whether $a and $b are not identical to each other in their
present operand types, and the answer is TRUE; they are not the
same.
COMPARISON OPERATORS
• Using comparison operators, you can test for more than just equality
and inequality.
• PHP also gives you > (is greater than), < (is less than), >= (is greater
than or equal to), and <= (is less than or equal to).
• EX:
• Example: The four comparison operators:
• <?php
• $a = 2; $b = 3;
• if ($a > $b) echo "$a is greater than $b <br>";
• if ($a < $b) echo "$a is less than $b“<br>;
• if ($a >= $b) echo "$a is greater than or equal to $b <br>";
• if ($a <= $b) echo "$a is less than or equal to $b <br>";
• ?>
• O/P: 2 is less than 3
• 2 is less than or equal to 3
LOGICAL OPERATORS
• Logical operators produce true-or-false results, and therefore are also
known as Boolean operators.
• Note that the ! symbol is required by PHP in place of NOT.
• Furthermore, the operators can be lower- or uppercase
• Example: The logical operators in use
• <?php
• $a = 1; $b = 0;
• echo ($a AND $b) . "<br>";
• echo ($a or $b) . "<br>";
• echo ($a XOR $b) . "<br>";
• echo !$a . "<br>";
• ?>
• This example outputs NULL, 1, 1, NULL, meaning that only the second
and third echo statements evaluate as TRUE.
• This is because the AND statement requires both operands to be
TRUE if it is going to return a value of TRUE, while the fourth
statement performs a NOT on the value of $a, turning it from TRUE (a
value of 1) to FALSE.
• The OR operator can cause unintentional problems in if statements,
because the second operand will not be evaluated if the first is
evaluated as TRUE.
• Example: A statement using the OR operator
• <?php
• if ($finished == 1 OR getnext() == 1) exit;
• ?>
• If you need getnext to be called at each if statement, you could
rewrite the code as has been done in following example,
• Example: The “if...OR” statement modified to ensure calling of
getnext
• <?php
• $gn = getnext();
• if ($finished == 1 OR $gn == 1) exit;
• ?>
• In this case, the code in function getnext will be executed and the
value returned stored in $gn before the if statement.
• Another solution is to switch the two clauses to make sure that get
next is executed, as it will then appear first in the expression.
• It shows all the possible variations of using the logical operators.
• Note that !TRUE equals FALSE, and !FALSE equals TRUE. All possible
PHP Logical expressions:
CONDITIONALS
• Conditionals alter program flow. They enable you to ask questions
about certain things and respond to the answers you get in different
ways.
• Conditionals are central to dynamic web pages—the goal of using PHP
in the first place—because they make it easy to create different output
each time a page is viewed.
• There are three types of non-looping conditionals
• 1. if statement
• 2. Switch statement
• 3. ? operator
• If statement:
• Syntax:
• if (condition) {
code to be executed if condition is true;
}
• Ex:
• <?php
• if ($bank_balance < 100)
•{
• $money = 1000;
• $bank_balance += $money;
•}
• ?>
• In this example, you are checking your balance to see whether it is
less than 100 dollars (or whatever your currency is).
• If so, you pay yourself 1,000 dollars and then add it to the balance. (If
only making money were that simple!)
• If the bank balance is 100 dollars or greater, the conditional
statements are ignored and program flow skips to the next line (not
shown).
• If-else statement:
• If you want to execute some code if a condition is true and another
code if a condition is false, use the if....else statement.
• Syntax:
• if (condition)
• code to be executed if condition is true;
• else
• code to be executed if condition is false;
• <?php
• if ($bank_balance < 100)
• {
• $money = 1000;
• $bank_balance += $money;
• }
• else
• {
• $savings += 50;
• $bank_balance -= 50;
• }
• ?>
• elseif statement:
• If you want to execute some code if one of the several conditions are true
use the elseif statement.
• Syntax:
• if (condition)
• code to be executed if condition is true;
• elseif (condition)
• code to be executed if condition is true;
• else
• code to be executed if condition is false;
• <?php
• if ($bank_balance < 100)
• {
• $money = 1000;
• $bank_balance += $money;
• }
• elseif ($bank_balance > 200)
• {
• $savings += 100;
• $bank_balance -= 100;
• }
• else
• {
• $savings += 50;
• $bank_balance -= 50;
• }
• ?>
• In the example, an elseif statement has been inserted between the if and
else statements.
• It checks whether your bank balance exceeds $200 and, if so, decides that
you can afford to save $100 of it this month.
• Switch statement:
• If you want to select one of many blocks of code to be executed, use
the Switch statement.
• The switch statement is used to avoid long blocks of if..elseif..else
code.
• Syntax:
• switch (expression){
• case label1:
• code to be executed if expression = label1;
• break;

• case label2:
• code to be executed if expression = label2;
• break;
• default:

• code to be executed
• if expression is different
• from both label1 and label2;
• }
• <html>
• <body>

• <?php
• $d = date("D");

• switch ($d){
• case "Mon":
• echo "Today is Monday";
• break;

• case "Tue":
• echo "Today is Tuesday";
• break;
• case "Wed":
• echo "Today is Wednesday";
• break;

• case "Thu":
• echo "Today is Thursday";
• break;

• case "Fri":
• echo "Today is Friday";
• break;

• case "Sat":
• echo "Today is Saturday";
• break;
• case "Sun":
• echo "Today is Sunday";
• break;

• default:
• echo "Wonder which day is this ?";
• }
• ?>
• </body>
• </html> O/P: Today is Monday
• Ternary operator:
• Syntax:
• $var = (condition)? value1 : value2;
• The ? operator is passed an expression that it must evaluate, along with
two statements to execute: one for when the expression evaluates to TRUE,
the other for when it is FALSE.
• EX:
• <?php
• echo $fuel <= 1 ? "Fill tank now" : "There's enough fuel";
• ?>
• You can also assign the value returned in a ? statement to a variable
• Assigning a ? conditional result to a variable
• <?php
• $enough = $fuel <= 1 ? FALSE : TRUE;
• ?>
LOOPING
• Loops in PHP are used to execute the same block of code a specified number of times.
PHP supports following four loop types.

• for − loops through a block of code a specified number of times.

• while − loops through a block of code if and as long as a specified condition is true.

• do...while − loops through a block of code once, and then repeats the loop as long as
a special condition is true.

• foreach − loops through a block of code for each element in an array.


• FOR STATEMENT:
• The initializer is used to set the start value for the counter of the
number of loop iterations. A variable may be declared here for this
purpose and it is traditional to name it $i.
SYNTAX:
• for (initialization; condition; increment){
• code to be executed;
•}
• <html>
• <body>
• <?php
• $a = 0;
• $b = 0;
• for( $i = 0; $i<5; $i++ ) {
• $a += 10;
• $b += 5;
• }
• echo ("At the end of the loop a = $a and b = $b" );
• ?>
• </body>
• </html> O/P: At the end of the loop a = 50 and b = 25
• WHILE LOOP statement:
• The while statement will execute a block of code if and as long as a
test expression is true.
• If the test expression is true then the code block will be executed.
After the code has executed the test expression will again be
evaluated and the loop will continue until the test expression is found
to be false.
• Syntax:
• while (condition) {
• code to be executed;
•}
• Example:
• This example decrements a variable value on each iteration of the loop
and the counter increments until it reaches 10 when the evaluation is
false and the loop ends.
• <html>
• <body>

• <?php
• $i = 0;
• $num = 50;

• while( $i < 10) {
• $num--;
• $i++;
• }

• echo ("Loop stopped at i = $i and num = $num" );
• ?>

• </body>
• do-while loop statement:
• The do...while statement will execute a block of code at least once - it
then will repeat the loop as long as a condition is true.
• Syntax:
• do {
• code to be executed;
•}
• while (condition);
• The following example will increment the value of i at least once, and
it will continue incrementing the variable i as long as it has a value of
less than 10.
• <html>
• <body>

• <?php
• $i = 0;
• $num = 0;

• do {
• $i++;
• }

• while( $i < 10 );
• echo ("Loop stopped at i = $i" );
• ?>

• </body>
• </html> O/P: Loop stopped at i = 10
• foreach loop statement:
• The foreach statement is used to loop through arrays. For each pass
the value of the current array element is assigned to $value and the
array pointer is moved by one and in the next pass next element will
be processed
• Syntax:
• foreach (array as value) {
• code to be executed;
•}
The following example to list out the values of an array.
• <html>
• <body>

• <?php
• $array = array( 1, 2, 3, 4, 5);

• foreach( $array as $value ) {
• echo "Value is $value <br />";
• }
• ?>
• </body>
• </html>
• o/p:
• Value is 1
• Value is 2
• Value is 3
• Value is 4
• Value is 5
• THE BREAK STATEMENT
• The PHP break keyword is used to terminate the execution of a loop
prematurely.
• The break statement is situated inside the statement block.
• It gives you full control and whenever you want to exit from the loop
you can come out.
• After coming out of a loop immediate statement to the loop will be
executed.
• <html>
• <body>

• <?php
• $i = 0;

• while( $i < 10) {
• $i++;
• if( $i == 3 )break;
• }
• echo ("Loop stopped at i = $i" );
• ?>

• </body>
• </html> O/P: Loop stopped at i = 3
• THE CONTINUE STATEMENT
• The PHP continue keyword is used to halt the current iteration of a
loop but it does not terminate the loop.
• Just like the break statement the continue statement is situated
inside the statement block containing the code that the loop
executes, preceded by a conditional test.
• For the pass encountering continue statement, rest of the loop code
is skipped and next pass starts.
• In the following example loop prints the value of array but for which condition
becomes true it just skip the code and next value is printed.
• <html>
• <body>

• <?php
• $array = array( 1, 2, 3, 4, 5);

• foreach( $array as $value ) {
• if( $value == 3 )continue;
• echo "Value is $value <br />";
• }
• ?>
• </body>
• </html>
• O/P:
• Value is 1
• Value is 2
• Value is 4
• Value is 5
IMPLICIT AND EXPLICIT CASTING
• Implicit Casting:
• PHP is a loosely typed language that allows you to declare a variable
and its type simply by using it.
• It also automatically converts values from one type to another
whenever required. This is called implicit casting.
• Example: This expression returns a floating-point number
• <?php
• $a = 56;
• $b = 12;
• $c = $a / $b;
• echo $c;
• ?>
• By default, PHP converts the output to floating point so it can give the
most precise value—4.66 recurring.
• Explicit casting:
• But what if we had wanted $c to be an integer instead?
• There are various ways in which we could achieve this, one of which is
to force the result of $a/$b to be cast to an integer value using the
integer cast type (int), like this:
• $c = (int) ($a / $b);
• Some casting types are tabulated as below:

You might also like