SlideShare une entreprise Scribd logo
1  sur  27
Télécharger pour lire hors ligne
SMG PHP NOTES 1
PHP is a popular general-purpose scripting language that is especially suited to web
development. It was originally created by Rasmus Lerdorf in 1994.
Advantages
PHP is Open Source
Large amount of databases are supported
PHP is platform independent
Compatible with servers
PHP frameworks built-in feature and tools make it easier to protect the web applications from
the outer attacks and security threats
PHP is also stable as compared to other programming languages. It has been in existence for
a long time. The developers have worked on PHP to make it easy for the programmers to
work on developing the PHP web-based applications.
Why use PHP
PHP is a server-side scripting language, which is used to design the dynamic web
applications with MySQL database.
 It handles dynamic content, database as well as session tracking for the website.
 It can access cookies variable and also set cookies.
 It helps to encrypt the data and apply validation.
 PHP supports several protocols such as HTTP, POP3, SNMP, LDAP, IMAP, and
many more.
 Using PHP language, you can control the user to access some pages of your website.
 As PHP is easy to install and set up, this is the main reason why PHP is the best
language to learn
Performance:
PHP script is executed much faster than those scripts which are written in other languages
such as JSP and ASP. PHP uses its own memory, so the server workload and loading time is
automatically reduced, which results in faster processing speed and better performance.
Open Source:
PHP source code and software are freely available on the web. You can develop all the
versions of PHP according to your requirement without paying any cost. All its components
are free to download and use.
Familiarity with syntax:
PHP has easily understandable syntax. Programmers are comfortable coding with it.
Embedded:
PHP code can be easily embedded within HTML tags and script.
Platform Independent:
PHP is available for WINDOWS, MAC, LINUX & UNIX operating system. A PHP
application developed in one OS can be easily executed in other OS also.
SMG PHP NOTES 2
Database Support:
PHP supports all the leading databases such as MySQL, SQLite, ODBC, etc.
Error Reporting -
PHP has predefined error reporting constants to generate an error notice or warning at
runtime. E.g., E_ERROR, E_WARNING, E_STRICT, E_PARSE.
Loosely Typed Language:
PHP allows us to use a variable without declaring its datatype. It will be taken automatically
at the time of execution based on the type of data it contains on its value.
Web servers Support:
PHP is compatible with almost all local servers used today like Apache, Netscape, Microsoft
IIS, etc.
Security:
PHP is a secure language to develop the website. It consists of multiple layers of security to
prevent threads and malicious attacks.
Control:
Different programming languages require long script or code, whereas PHP can do the same
work in a few lines of code. It has maximum control over the websites like you can make
changes easily whenever you want.
SMG PHP NOTES 3
How to install PHP
XAMPP (/ˈzæmp/ or /ˈɛks.æmp/) is a free and open-source cross-platform web server
solution stack package developed by Apache Friends, consisting mainly of the Apache HTTP
Server, MariaDB database, and interpreters for scripts written in the PHP and Perl
programming languages
Figure 1 select XAMPP from start menu
Figure 2XAMPP control panel
Figure 3 Apache starting
SMG PHP NOTES 4
Figure 4 Apache Ready Stage
Getting started
Doesn’t need any special software, except text editor like Notepad
In order to save php script to the hard disk, the filename.php
Save the file in root folder of xamp(C:xampphtdocsfirst.php)
The scripts must placed between the<?php And ?> delimiters.
Example Program first.php
<?php
echo "<b>This is first programme in PHP! welcome Guys</b>";
?>
Goto any browser on address bar just enter localhost/first.php
Note
Should be semicolon (;) end of a PHP statement and never to forgotten.
SMG PHP NOTES 5
Figure 5 OUTPUT
Varaibles
All variables in PHP start with a $ sign, followed by the name of the variable.
A variable name must start with a letter or the underscore character
A variable name cannot start with a number
A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _)
Variable names are case-sensitive ($age and $AGE are two different variables)
Declaring variable
$var_name=value; not valid vraibles
Ex ex
$age=19; $1er=123;
$name=“karthick”; $*qw=”sorry”;
$amount=45.89;
Variable Scope
Each variable has a memory in which it’s known as its scope, that means variable have the
scope of page in they reside. If function have their own scope which means own variable
used in function are not available outside run of the function. For example if PHP programme
has several $b in a program, however there’s only one active at any specific instance in time.
So why the scope of variable is important. The variables that are declared within a function
are called local variables for that function. These local variables have their scope only in that
particular function in which they are declared. This means that these variables cannot be
accessed outside the function, as they have local scope.
The global variables are the variables that are declared outside the function. These
variables can be accessed anywhere in the program. To access the global variable within a
function, use the GLOBAL keyword before the variable.
<?php
function myfun() //function Creation
{
$var=”hai welcome”;
}
myfun(); //function call
echo”$var”; //it gives error during run this programme
SMG PHP NOTES 6
?>
<?php
function myfun() //function Creation
{
global $var=”hai welcome”; //declared as global
}
myfun(); //function call
echo”$var”; //now we access the variable from outside
?>
Constants
A constant is an identifier (name) for a simple value. As the name suggests, that value
cannot change during the execution of the script. A constant is case-sensitive by default
should follow the variables rules to define a constant. There is no need $(dollar symbol).
Syntax
define(“<constantname>”,<expr> [,<casesensitive>]);
Example
define(“stringcons”,”hai welcome”);
define(“intcons”,2000);
define(“pi”,3.14);
Data types
String
Strings are sequences of characters that are always internally NULL terminated. There
is no limit to size
Eg $str=”hai how are you”;
Integer
It holds whole numbers, it can be specified in decimal (base 10), hexadecimal (base
16 - prefixed with 0x) or octal (base 8 - prefixed with 0) notation, optionally preceded by a
sign (- or +). There is a maximum limit from -2147483647(-231
) to +2147483647(+231
).
Float
Floating point numbers that holds high integer values or fractional numbers
Eg $pi=3.14;
Boolean
Booleans are like a switch it has only two possible values either 1 (true) or 0 (false).
Arrays
An array is a variable that can hold more than one value at a time. It is useful to
aggregate a series of related items together. Eg
$weekdays=(“Sunday”,”Monday”,”Tuesday”);
Objects
Object variable are complex variables that holds own properties and methods for
accessing or manipulating their content.
Resource
A resource is a special variable that hold anything that is not PHP data. Resource
variables typically hold special handlers to opened files and database connections.
To display text as output
To output text in a PHP script to a browser print or echo is command which tells the
PHP interpreter what do.
Print
Print is also a statement used to display the output. it can be used with parentheses
print( ) or without parentheses print.
using print can doesn't pass multiple argument
SMG PHP NOTES 7
it’s slower
ex print(“hai”);
echo
echo is a statement used to display the output. it can be used with parentheses echo or
without parentheses echo. It can pass multiple string separated as (, ). Its faster than print
ex echo(“hai”);
Superglobals
Superglobals are variables do not have a fixed scope they are available in all of them,
they provide as follows
 Useful information about the environment
 Allow to access to HTML form variables or parenthesis
 Access to cookies stored on a client
 Keeping tracking session and file uploads
$_GET : $_GET is a super global variable used to collect data from the HTML form after
submitting it. $_GET super global array variable stores the values that come in the URL.
$_POST: superglobal is needed in order to pass PHP variables or collect data from forms
after they have been submitted via an HTML form. It’s similar to $_GET, conventionally
used the contents of an HTML form are going to change values in database permanently.
$_REQUEST: It is a superglobal variable which is used to collect the data after submitting a
HTML form.it’s similar to $_GET and $_POST variables. $_REQUEST is not used mostly,
because $_POST and $_GET perform the same task and are widely used.
$GLOBALS : It is a superglobal variable which is used to access global variables from
anywhere in the PHP script. PHP stores all the global variables in array $GLOBALS where
index holds the global variable name.
$_COOKIE – contains all variables passed to HTTP Cookies.
$_SERVER: set by the web server or otherwise directly related to current environment the
script.
$_SESSION – holds the variables which are currently registered script.
$_ENV - An associative of variables passed to the current script via the environment method
$_FILES – holds variables are uploaded to the current script via the HTTP POST method.
Here documents
Here documents a special form of I/O redirection to feed command list to an
interactive program or command.
If you need to set in your PHP script a string containing big chunk of text data it is
easier to use "here document" style.
This special way allows you to set multiline strings, with all included variables
expanded as it is done in double quotes style.
Save as C:xampphtdocsprogramsheredoc.php
Start Apache server
Run in any Browser http://localhost/programs/heredoc.php
<?php
$heremes=<<<EOF
<b>list of books</b>
<ol>
<li>java
<li>Programming in C
<li>OOP with C++
<li>PHP and HTML
</ol>
SMG PHP NOTES 8
EOF;
echo($heremes);
?>
Output will be
Arithmetic operator
Here are following arithmetic operators supported by PHP language −
Assume variable A holds 10 and variable B holds 5 then −
Operator Description Example
+ Adds two operands $A + $B will give 15
- Subtracts second operand from the first $A - $B will give 5
* Multiply both operands $A * $B will give 50
/ Divide numerator by de-numerator $A / $B will give 2
% Modulus Operator and remainder of after an integer division $A % $B will give 0
++ Increment operator, increases integer value by one $A++ will give 11
-- Decrement operator, decreases integer value by one $A-- will give 9
Concatenates
The concatenation operator (‘.‘), which returns the concatenation of its right and left
arguments (join two arguments).
<?php
$a=10;
$b=20;
$c=$a+$b;
SMG PHP NOTES 9
echo ”the addition of value of c=“.$c;
?>
OUTPUT
the addition of c=30
Logical operator
The logical operators are used when we want, test more than one condition
Operator Description
&&, and Called Logical AND operator. If both the operands are non-zero, then the condition becomes
true.
||,or,|| Called Logical OR Operator. If any of the two operands is non-zero, then the condition
becomes true.
! Called Logical NOT Operator. It is used to reverse the logical state of its operand. If a
condition is true, then Logical NOT operator will make it false.
Comparison Operator
We often compare two quantities and depending on their relation, take certain decisions
Operator Description
== 3==9 returns false
!= 3!=9 returns true.
> 3>9 returns false
< 3<9 returns true
>= Checks if the value of left operand is greater than or equal to the value of right
operand. If yes, then the condition becomes true. 15>=18 returns false
<= Checks if the value of left operand is less than or equal to the value of right
operand. If yes, then the condition becomes true. 15<=18 returns true
=== Identical that means 3===3 returns true
!== Is not identical 8!==“8” returns true
SMG PHP NOTES 10
Assignment operator
The assignment operators are used to assign values result of an expression to a
variable assigns values from right side operands to left side operand
Operator Description Example
= Simple assignment operator. $C = $A + $B will assign the value of $A +
$B to $C
+= Add AND assignment operator. $C+= $A is equivalent to $C = $C + $A
-= Subtract AND assignment
operator.
$C -= $A is equivalent to $C = $C - $A
*= Multiply AND assignment
operator.
$C *= $A is equivalent to $C = $C * $A
/= Divide AND assignment
operator.
$C /= $A is equivalent to $C = $C / $A
%= Modulus AND assignment
operator.
$C %= $A is equivalent to $C = $C % $A
Increment and decrement
Increment ++ increases the value by 1 whereas decrement -- decreases the value by 1.
++ operator as prefix like: ++$var. The value of var is incremented by 1 then, it returns the
value.
use ++ operator as postfix like: $var++. The original value of var is returned first then, var is
incremented by 1
Bitwise Operator
The Bitwise operators is used to perform bit-level operations on the operands. The
operators are first converted to bit-level (Binary Digit) and then calculation is performed on
the operands.
Operator Meaning
Bitwise
AND &
This is a binary operator. Bitwise AND operator in PHP takes two numbers
as operands and does AND on every bit of two numbers. The result of AND
is 1 only if both bits are 1.
Bitwise OR
|
This is also binary operator. Bitwise OR operator takes two numbers as
operands and does OR on every bit of two numbers. The result of OR is 1
any of the two bits is 1.
Bitwise
XOR ^
This is also binary operator. Bitwise XOR takes two numbers as operands
and does XOR on every bit of two numbers. The result of XOR is 1 if the
two bits are different.
SMG PHP NOTES 11
Numbers/
Bit level
23=8 22=4 21=2 20=1 Result
4 0 1 0 0
5 0 1 0 1
Bitwise AND & 0 1 0 0 4
Bitwise OR | 0 1 0 1 5
Bitwise OR ^ 0 0 0 1 1
Example
<?php
$a=5;
$b=4;
$c=$a&$b;
$d=$a|$b;
$e=$a^$b;
echo"BitwiseAND$c"."<br>";
echo"BitwiseOR$d"."<br>";
echo"BitwiseXOR$e"."<br>";
?>
Output
Ternary Operator
In simple words, PHP Ternary Operator is a shortened method of writing an if-else
statement.
Syntax
$condition ? 'true result' : 'false result';
Example
<?php
$n=11;
$ans=($n%2==0)?"even number":"odd number";
echo $ans;
?>
SMG PHP NOTES 12
Output
Reference
When the = operator is used, PHP performs a copy operation. References allow two
variables to refer to the same content. The ampersand (&) is placed before the variable to be
referenced. Once two variables are pointing to the same data, either of variables can be
changed and the other one will also be updated.
Example
<?php
$a=5;
$b=&$a;
echo"before update a=$a"."<br>";
echo"before update b=$b"."<br>";
$a++;
echo "After update a=$a and b=$b"."<br>";
$b++;
echo "now b update a=$a and b=$b"."<br>";
?>
SMG PHP NOTES 13
Output
Precedence of PHP Operators
Operator precedence determines the grouping of terms in an expression. This affects
how an expression is evaluated.
For example x = 7 + 3 * 2; Here x is assigned 13, not 20 because operator * has
higher precedence than + so it first get multiplied with 3*2 and then adds into 7.
Category Operator Associativity
Unary ! ++ -- Right to left
Multiplicative * / % Left to right
Additive + - Left to right
Relational < <= > >= Left to right
Equality == != Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %= Right to left
SMG PHP NOTES 14
Arrays
An array is a special variable, which can hold more than one value at a time.
Array is differs from normal variable when it’s created and its being accessed. To store array
values in an array use square bracket ([ ]).
$a[0] = "one";
$a[1] = "two";
$a[2] = "three";
$a[3] = "four";
$a[4] = "five";
Alternatively PHP provides function that allows to create an array. The above data
inserted into an array using the function array() as follows:
$a=array(0=>”one”,1=>”two”,2=>”three”,3=>”four”,4=>”five”);
To access array values as follows
echo $a[0];
echo $a[1];
Associate Arrays
The associative arrays are very similar to arrays in term of functionality but they are
different in terms of their index. Associative array will have their index as string.
$student[‘name’]=”Ram”;
$student[‘mark’]=40;
To access associate array values as follows
echo”hi Mr”.$$student[‘name’] . “you got”.$student[‘mark’];
SMG PHP NOTES 15
Conditional statements
PHP lets programmers evaluate different conditions during of a program and take
decisions based on whether these conditions evaluate to true of false. These conditions, and
the actions associated with them, are expressed by means of a programming construct called
a conditional statement. They are
If else
The if...else statement allows you to execute one block of code if the specified
condition is evaluates to true and another block of code if it is evaluates to false.
Syntax
if(condition)
{
true statement;
}
else
{
False statement;
}
Example program
<?php
$month=date("M");/*Returns a string formatted according to the given format */
if($month=="May")
{
echo"This month is May"."<br>";
echo"its starting stage of Summer Season";
}
else
{
echo$month;
}
?>
SMG PHP NOTES 16
Output
From the above example current month assigned to the variable $month, then check is made
as to whether variable holds value May. If value is May executed true statement, otherwise
returns false statement.
The elseif clause
The if-else-if-else statement lets chain together multiple if-else statements used
conduct a serial of conditional checks and only executes the first condition that is met.
Syntax
if(condition1)
{
executed if condition1 is true;
}
elseif(condition2)
{
executed if the condition1 is false and condition2 is true;
}
else
{
executed if both condition1 and condition2 are false;
}
SMG PHP NOTES 17
Example
<?php
$month=date("M");
if($month=="Jan")
{
echo"This month is January"."<br>";
echo"Numeric value is 1";
}
elseif($month=="Feb")
{
echo"This month is February"."<br>";
echo"Numeric value is 2";
}
elseif($month=="Mar")
{
echo"This month is March"."<br>";
echo"Numeric value is 3";
}
elseif($month=="Apr")
{
echo"This month is April"."<br>";
echo"Numeric value is 4";
}
elseif($month=="May")
{
echo"This month is May"."<br>";
echo"Numeric value is 5";
}
elseif($month=="Jun")
{
echo"This month is June"."<br>";
echo"Numeric value is 6";
}
else
{
echo$month;
}
?>
SMG PHP NOTES 18
Output
The above code starts by extracting the month and storing into $month. A check is made if
extracted month is January the returns TRUE, executes current statement. If condition is
FALSE checks next condition this process continues until either appropriate code block is
executed or else clause (FALSE statement).
Another method of achieve same functionality using elseif clause
<?php
$a=5;
$b=9;
$c=20;
if($a>$b&&$a>$c)
{
print"$a is big";
}
else { if ($b>$a&&$b>$c)
{
print"$b is big";
}
else
{
print"$c is big";
}
}
?>
SMG PHP NOTES 19
The switch statement
The switch-case statement is an alternative to the if-elseif-else statement, which does
almost the same thing. The switch-case statement tests a variable against a series of values
until it finds a match, and then executes the block of code corresponding to that match.
The switch statement is given an expression. This expression compared to all
possible expression listed in its body. On successful match, the code block under that
particular case expression is executed, after all code spec terminates because of explicit break
which mentioned in each case section.
Syntax
switch(expression)
{
case label1:
//code to be executed
break;
case label2:
//code to be executed
break;
......
default:
code to be executed if all cases are not matched;
}
Example
<?php
$d=date("D");
switch($d)
{
case "Mon":
print"its monday";
echo'<body style="background-color:green">';
break;
case "Tue":
print"its Tuesday";
echo'<body style="background-color:red">';
break;
case "Wed":
echo'<body style="background-color:yellow">';
print"its Wednesday";
break;
case "Thu":
print"its Thursday";
echo'<body style="background-color:#999900">';
break;
case "Fri":
print"its Friday";
echo'<body style="background-color:blue">';
break;
case "Sat":
print"its Saturday";
echo'<body style="background-color:ff66ff">';
SMG PHP NOTES 20
break;
case "Sun":
print"its Sunday";
echo'<body style="background-color:orange">';
break;
default:
print"none of the above";
}
?>
Output
SMG PHP NOTES 21
Looping
Execution of a statement or set of statement repeatedly is called as looping. The loop may be
executed a specified number of times and this depends on the satisfaction of a test condition.
In PHP the following loop statements are available
For- loops through a block of code specified number of times
While- loops through a block of code as long as specified condition is TRUE
Do..while - loops through a block of code at least once and repeated as long as specified
condition is TRUE
Foreach- loops through the elements of an array. Works only on arrays. Will throw an error
when used with a variable of a different data type or an un-initialized variable.
The for loop
Loops through a block of code specified number of times. The general structure of for
loop
for (initialization; test condition; increment)
{
body of the loop
}
initialize : Initialize the loop counter value state of variable to be tested, normally done by
assignment operator.
test condition: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues.
If it evaluates to FALSE, the loop ends.
increment : Increases the loop counter value
When the control enters for loop the variables used in for loop is initialized with the
starting value
The value which was initialized is then checked with the given test condition. The test
condition is a relational expression, such as I < 5 that checks whether the given condition is
satisfied or not if the given condition is satisfied the control enters the body of the loop or
else it will exit the loop.
The body of the loop is entered only if the test condition is satisfied and after the
completion of the execution of the loop the control is transferred back to the increment part of
the loop. The control variable is incremented using an assignment statement such as I=I+1 or
simply I++ and the new value of the control variable is again tested to check whether it satisfies
the loop condition. If the value of the control variable satisfies then the body of the loop is
again executed. The process goes on till the control variable fails to satisfy the condition
SMG PHP NOTES 22
Example
<?php
for($i=1;$i<=10;$i++)
{
echo"<b>The value is $i<br/></b>";
}
Output
SMG PHP NOTES 23
While loop
The while loop executes a block of code as long as the specified condition is true.
Syntax
while (condition is true)
{
code to be executed;
}
Here the given test condition is evaluated and if the condition is true then the body of the loop
is executed. After the execution of the body, the test condition is once again evaluated and if
it is true, the body is executed once again. This process of repeated execution of the body
SMG PHP NOTES 24
continues until the test condition finally becomes false and the control is transferred out of
the loop.
Example
<?php
$ctr=1;
while($ctr<=16)
{
echo"<b>5X$ctr=</b>".(5*$ctr)."<br/>";
$ctr++;
}
?>
Output
Controlling Array using while Loop
Often while loop is used to run through an array as follows
while(list($key,$val)=each($array)
{
echo “ key=> $val”;
}
Example
<?php
$array=array(‘Tamilnadu’=>’Chennai’,’Goa’=>’panji’,’Maharashtra’=>’Mumbai’);
while($list($key,$value)=each($array))
{
echo $key.”<br>”;
echo $value. “<br>’;
?>
The do...while Loop
The do...while loop will always execute the block of code once, it will then check the
condition, and repeat the loop while the specified condition is true.
Syntax
do
SMG PHP NOTES 25
{
code to be executed;
} while (condition is true);
Here the statement is executed, then expression is evaluated. If the condition expression is
true then the body is executed again and this process continues till the conditional expression
becomes false. When the expression becomes false. When the expression becomes false the
loop terminates.
Example
<?php
$i=0;
do
{
$i++;
echo $i."<br>";
}while($i<10);
?>
Output
SMG PHP NOTES 26
foreach Loop
The foreach loop is used to iterate over arrays.
foreach($array as $value)
{
// Code to be executed;
}
Example
<?php
$name=array('Ram','Seetha','Ajay','Kumar','Pari','Karthick');//array creation
$n=1;
foreach ($name as $value)
{
echo"The name is in position $n:$value"."<br>";
$n++;
}
?>
Output
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.
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.
SMG PHP NOTES 27
For the pass encountering continue statement, rest of the loop code is skipped and next pass
starts.

Contenu connexe

Tendances

Software Engineering (Software Process: A Generic View)
Software Engineering (Software Process: A Generic View)Software Engineering (Software Process: A Generic View)
Software Engineering (Software Process: A Generic View)ShudipPal
 
ASP.NET MVC Presentation
ASP.NET MVC PresentationASP.NET MVC Presentation
ASP.NET MVC PresentationVolkan Uzun
 
Designing Techniques in Software Engineering
Designing Techniques in Software EngineeringDesigning Techniques in Software Engineering
Designing Techniques in Software Engineeringkirupasuchi1996
 
Software cost estimation techniques presentation
Software cost estimation techniques presentationSoftware cost estimation techniques presentation
Software cost estimation techniques presentationKudzai Rerayi
 
PHP Frameworks and CodeIgniter
PHP Frameworks and CodeIgniterPHP Frameworks and CodeIgniter
PHP Frameworks and CodeIgniterKHALID C
 
CSS3 Media Queries
CSS3 Media QueriesCSS3 Media Queries
CSS3 Media QueriesRuss Weakley
 
Angular tutorial
Angular tutorialAngular tutorial
Angular tutorialRohit Gupta
 
software process improvement
software process improvementsoftware process improvement
software process improvementMohammad Xaviar
 
ASP.NET Presentation
ASP.NET PresentationASP.NET Presentation
ASP.NET Presentationdimuthu22
 
Introduction to Cascading Style Sheets (CSS)
Introduction to Cascading Style Sheets (CSS)Introduction to Cascading Style Sheets (CSS)
Introduction to Cascading Style Sheets (CSS)Chris Poteet
 
Coding standards for java
Coding standards for javaCoding standards for java
Coding standards for javamaheshm1206
 
Modules and modularization criteria
Modules and modularization criteriaModules and modularization criteria
Modules and modularization criteriaUmaselvi_R
 

Tendances (20)

Software Engineering (Software Process: A Generic View)
Software Engineering (Software Process: A Generic View)Software Engineering (Software Process: A Generic View)
Software Engineering (Software Process: A Generic View)
 
Static analysis
Static analysisStatic analysis
Static analysis
 
Php tutorial
Php  tutorialPhp  tutorial
Php tutorial
 
unit testing and debugging
unit testing and debuggingunit testing and debugging
unit testing and debugging
 
ASP.NET MVC Presentation
ASP.NET MVC PresentationASP.NET MVC Presentation
ASP.NET MVC Presentation
 
Designing Techniques in Software Engineering
Designing Techniques in Software EngineeringDesigning Techniques in Software Engineering
Designing Techniques in Software Engineering
 
Software cost estimation techniques presentation
Software cost estimation techniques presentationSoftware cost estimation techniques presentation
Software cost estimation techniques presentation
 
PHP variables
PHP  variablesPHP  variables
PHP variables
 
PHP Frameworks and CodeIgniter
PHP Frameworks and CodeIgniterPHP Frameworks and CodeIgniter
PHP Frameworks and CodeIgniter
 
Chapter 01
Chapter 01Chapter 01
Chapter 01
 
CSS3 Media Queries
CSS3 Media QueriesCSS3 Media Queries
CSS3 Media Queries
 
Javascript
JavascriptJavascript
Javascript
 
Angular tutorial
Angular tutorialAngular tutorial
Angular tutorial
 
software process improvement
software process improvementsoftware process improvement
software process improvement
 
ASP.NET Presentation
ASP.NET PresentationASP.NET Presentation
ASP.NET Presentation
 
Introduction to Cascading Style Sheets (CSS)
Introduction to Cascading Style Sheets (CSS)Introduction to Cascading Style Sheets (CSS)
Introduction to Cascading Style Sheets (CSS)
 
Coding standards for java
Coding standards for javaCoding standards for java
Coding standards for java
 
Xml namespace
Xml namespaceXml namespace
Xml namespace
 
JavaScript
JavaScriptJavaScript
JavaScript
 
Modules and modularization criteria
Modules and modularization criteriaModules and modularization criteria
Modules and modularization criteria
 

Similaire à Php notes (20)

Php Tutorial
Php TutorialPhp Tutorial
Php Tutorial
 
chapter 5 Server-Side Scripting (PHP).pdf
chapter 5 Server-Side Scripting (PHP).pdfchapter 5 Server-Side Scripting (PHP).pdf
chapter 5 Server-Side Scripting (PHP).pdf
 
Php ppt
Php pptPhp ppt
Php ppt
 
PHP
PHPPHP
PHP
 
Introduction to-php
Introduction to-phpIntroduction to-php
Introduction to-php
 
Php1
Php1Php1
Php1
 
Php1
Php1Php1
Php1
 
Php1
Php1Php1
Php1
 
Php tutorial from_beginner_to_master
Php tutorial from_beginner_to_masterPhp tutorial from_beginner_to_master
Php tutorial from_beginner_to_master
 
PHP Basic & Variables
PHP Basic & VariablesPHP Basic & Variables
PHP Basic & Variables
 
Php basics
Php basicsPhp basics
Php basics
 
WT_PHP_PART1.pdf
WT_PHP_PART1.pdfWT_PHP_PART1.pdf
WT_PHP_PART1.pdf
 
PHP
PHPPHP
PHP
 
PHP NOTES FOR BEGGINERS
PHP NOTES FOR BEGGINERSPHP NOTES FOR BEGGINERS
PHP NOTES FOR BEGGINERS
 
Chap 4 PHP.pdf
Chap 4 PHP.pdfChap 4 PHP.pdf
Chap 4 PHP.pdf
 
Php introduction
Php introductionPhp introduction
Php introduction
 
PHP - Introduction to PHP Fundamentals
PHP -  Introduction to PHP FundamentalsPHP -  Introduction to PHP Fundamentals
PHP - Introduction to PHP Fundamentals
 
php basics
php basicsphp basics
php basics
 
Php
PhpPhp
Php
 
PHP Basics
PHP BasicsPHP Basics
PHP Basics
 

Plus de Muthuganesh S

Plus de Muthuganesh S (12)

javascript.pptx
javascript.pptxjavascript.pptx
javascript.pptx
 
OR
OROR
OR
 
Operation Research VS Software Engineering
Operation Research VS Software EngineeringOperation Research VS Software Engineering
Operation Research VS Software Engineering
 
Cnotes
CnotesCnotes
Cnotes
 
CSS
CSSCSS
CSS
 
Conditional statement in c
Conditional statement in cConditional statement in c
Conditional statement in c
 
Input output statement in C
Input output statement in CInput output statement in C
Input output statement in C
 
Php Basics Iterations, looping
Php Basics Iterations, loopingPhp Basics Iterations, looping
Php Basics Iterations, looping
 
PHP Basics
PHP BasicsPHP Basics
PHP Basics
 
Php
PhpPhp
Php
 
Introduction to c
Introduction to cIntroduction to c
Introduction to c
 
Javascript dom
Javascript domJavascript dom
Javascript dom
 

Dernier

Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and ModificationsMJDuyan
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Association for Project Management
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701bronxfugly43
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxDr. Sarita Anand
 
Dyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptxDyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptxcallscotland1987
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibitjbellavia9
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsKarakKing
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Jisc
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxheathfieldcps1
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...pradhanghanshyam7136
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - Englishneillewis46
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxJisc
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024Elizabeth Walsh
 

Dernier (20)

Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
Dyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptxDyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptx
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 

Php notes

  • 1. SMG PHP NOTES 1 PHP is a popular general-purpose scripting language that is especially suited to web development. It was originally created by Rasmus Lerdorf in 1994. Advantages PHP is Open Source Large amount of databases are supported PHP is platform independent Compatible with servers PHP frameworks built-in feature and tools make it easier to protect the web applications from the outer attacks and security threats PHP is also stable as compared to other programming languages. It has been in existence for a long time. The developers have worked on PHP to make it easy for the programmers to work on developing the PHP web-based applications. Why use PHP PHP is a server-side scripting language, which is used to design the dynamic web applications with MySQL database.  It handles dynamic content, database as well as session tracking for the website.  It can access cookies variable and also set cookies.  It helps to encrypt the data and apply validation.  PHP supports several protocols such as HTTP, POP3, SNMP, LDAP, IMAP, and many more.  Using PHP language, you can control the user to access some pages of your website.  As PHP is easy to install and set up, this is the main reason why PHP is the best language to learn Performance: PHP script is executed much faster than those scripts which are written in other languages such as JSP and ASP. PHP uses its own memory, so the server workload and loading time is automatically reduced, which results in faster processing speed and better performance. Open Source: PHP source code and software are freely available on the web. You can develop all the versions of PHP according to your requirement without paying any cost. All its components are free to download and use. Familiarity with syntax: PHP has easily understandable syntax. Programmers are comfortable coding with it. Embedded: PHP code can be easily embedded within HTML tags and script. Platform Independent: PHP is available for WINDOWS, MAC, LINUX & UNIX operating system. A PHP application developed in one OS can be easily executed in other OS also.
  • 2. SMG PHP NOTES 2 Database Support: PHP supports all the leading databases such as MySQL, SQLite, ODBC, etc. Error Reporting - PHP has predefined error reporting constants to generate an error notice or warning at runtime. E.g., E_ERROR, E_WARNING, E_STRICT, E_PARSE. Loosely Typed Language: PHP allows us to use a variable without declaring its datatype. It will be taken automatically at the time of execution based on the type of data it contains on its value. Web servers Support: PHP is compatible with almost all local servers used today like Apache, Netscape, Microsoft IIS, etc. Security: PHP is a secure language to develop the website. It consists of multiple layers of security to prevent threads and malicious attacks. Control: Different programming languages require long script or code, whereas PHP can do the same work in a few lines of code. It has maximum control over the websites like you can make changes easily whenever you want.
  • 3. SMG PHP NOTES 3 How to install PHP XAMPP (/ˈzæmp/ or /ˈɛks.æmp/) is a free and open-source cross-platform web server solution stack package developed by Apache Friends, consisting mainly of the Apache HTTP Server, MariaDB database, and interpreters for scripts written in the PHP and Perl programming languages Figure 1 select XAMPP from start menu Figure 2XAMPP control panel Figure 3 Apache starting
  • 4. SMG PHP NOTES 4 Figure 4 Apache Ready Stage Getting started Doesn’t need any special software, except text editor like Notepad In order to save php script to the hard disk, the filename.php Save the file in root folder of xamp(C:xampphtdocsfirst.php) The scripts must placed between the<?php And ?> delimiters. Example Program first.php <?php echo "<b>This is first programme in PHP! welcome Guys</b>"; ?> Goto any browser on address bar just enter localhost/first.php Note Should be semicolon (;) end of a PHP statement and never to forgotten.
  • 5. SMG PHP NOTES 5 Figure 5 OUTPUT Varaibles All variables in PHP start with a $ sign, followed by the name of the variable. A variable name must start with a letter or the underscore character A variable name cannot start with a number A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _) Variable names are case-sensitive ($age and $AGE are two different variables) Declaring variable $var_name=value; not valid vraibles Ex ex $age=19; $1er=123; $name=“karthick”; $*qw=”sorry”; $amount=45.89; Variable Scope Each variable has a memory in which it’s known as its scope, that means variable have the scope of page in they reside. If function have their own scope which means own variable used in function are not available outside run of the function. For example if PHP programme has several $b in a program, however there’s only one active at any specific instance in time. So why the scope of variable is important. The variables that are declared within a function are called local variables for that function. These local variables have their scope only in that particular function in which they are declared. This means that these variables cannot be accessed outside the function, as they have local scope. The global variables are the variables that are declared outside the function. These variables can be accessed anywhere in the program. To access the global variable within a function, use the GLOBAL keyword before the variable. <?php function myfun() //function Creation { $var=”hai welcome”; } myfun(); //function call echo”$var”; //it gives error during run this programme
  • 6. SMG PHP NOTES 6 ?> <?php function myfun() //function Creation { global $var=”hai welcome”; //declared as global } myfun(); //function call echo”$var”; //now we access the variable from outside ?> Constants A constant is an identifier (name) for a simple value. As the name suggests, that value cannot change during the execution of the script. A constant is case-sensitive by default should follow the variables rules to define a constant. There is no need $(dollar symbol). Syntax define(“<constantname>”,<expr> [,<casesensitive>]); Example define(“stringcons”,”hai welcome”); define(“intcons”,2000); define(“pi”,3.14); Data types String Strings are sequences of characters that are always internally NULL terminated. There is no limit to size Eg $str=”hai how are you”; Integer It holds whole numbers, it can be specified in decimal (base 10), hexadecimal (base 16 - prefixed with 0x) or octal (base 8 - prefixed with 0) notation, optionally preceded by a sign (- or +). There is a maximum limit from -2147483647(-231 ) to +2147483647(+231 ). Float Floating point numbers that holds high integer values or fractional numbers Eg $pi=3.14; Boolean Booleans are like a switch it has only two possible values either 1 (true) or 0 (false). Arrays An array is a variable that can hold more than one value at a time. It is useful to aggregate a series of related items together. Eg $weekdays=(“Sunday”,”Monday”,”Tuesday”); Objects Object variable are complex variables that holds own properties and methods for accessing or manipulating their content. Resource A resource is a special variable that hold anything that is not PHP data. Resource variables typically hold special handlers to opened files and database connections. To display text as output To output text in a PHP script to a browser print or echo is command which tells the PHP interpreter what do. Print Print is also a statement used to display the output. it can be used with parentheses print( ) or without parentheses print. using print can doesn't pass multiple argument
  • 7. SMG PHP NOTES 7 it’s slower ex print(“hai”); echo echo is a statement used to display the output. it can be used with parentheses echo or without parentheses echo. It can pass multiple string separated as (, ). Its faster than print ex echo(“hai”); Superglobals Superglobals are variables do not have a fixed scope they are available in all of them, they provide as follows  Useful information about the environment  Allow to access to HTML form variables or parenthesis  Access to cookies stored on a client  Keeping tracking session and file uploads $_GET : $_GET is a super global variable used to collect data from the HTML form after submitting it. $_GET super global array variable stores the values that come in the URL. $_POST: superglobal is needed in order to pass PHP variables or collect data from forms after they have been submitted via an HTML form. It’s similar to $_GET, conventionally used the contents of an HTML form are going to change values in database permanently. $_REQUEST: It is a superglobal variable which is used to collect the data after submitting a HTML form.it’s similar to $_GET and $_POST variables. $_REQUEST is not used mostly, because $_POST and $_GET perform the same task and are widely used. $GLOBALS : It is a superglobal variable which is used to access global variables from anywhere in the PHP script. PHP stores all the global variables in array $GLOBALS where index holds the global variable name. $_COOKIE – contains all variables passed to HTTP Cookies. $_SERVER: set by the web server or otherwise directly related to current environment the script. $_SESSION – holds the variables which are currently registered script. $_ENV - An associative of variables passed to the current script via the environment method $_FILES – holds variables are uploaded to the current script via the HTTP POST method. Here documents Here documents a special form of I/O redirection to feed command list to an interactive program or command. If you need to set in your PHP script a string containing big chunk of text data it is easier to use "here document" style. This special way allows you to set multiline strings, with all included variables expanded as it is done in double quotes style. Save as C:xampphtdocsprogramsheredoc.php Start Apache server Run in any Browser http://localhost/programs/heredoc.php <?php $heremes=<<<EOF <b>list of books</b> <ol> <li>java <li>Programming in C <li>OOP with C++ <li>PHP and HTML </ol>
  • 8. SMG PHP NOTES 8 EOF; echo($heremes); ?> Output will be Arithmetic operator Here are following arithmetic operators supported by PHP language − Assume variable A holds 10 and variable B holds 5 then − Operator Description Example + Adds two operands $A + $B will give 15 - Subtracts second operand from the first $A - $B will give 5 * Multiply both operands $A * $B will give 50 / Divide numerator by de-numerator $A / $B will give 2 % Modulus Operator and remainder of after an integer division $A % $B will give 0 ++ Increment operator, increases integer value by one $A++ will give 11 -- Decrement operator, decreases integer value by one $A-- will give 9 Concatenates The concatenation operator (‘.‘), which returns the concatenation of its right and left arguments (join two arguments). <?php $a=10; $b=20; $c=$a+$b;
  • 9. SMG PHP NOTES 9 echo ”the addition of value of c=“.$c; ?> OUTPUT the addition of c=30 Logical operator The logical operators are used when we want, test more than one condition Operator Description &&, and Called Logical AND operator. If both the operands are non-zero, then the condition becomes true. ||,or,|| Called Logical OR Operator. If any of the two operands is non-zero, then the condition becomes true. ! Called Logical NOT Operator. It is used to reverse the logical state of its operand. If a condition is true, then Logical NOT operator will make it false. Comparison Operator We often compare two quantities and depending on their relation, take certain decisions Operator Description == 3==9 returns false != 3!=9 returns true. > 3>9 returns false < 3<9 returns true >= Checks if the value of left operand is greater than or equal to the value of right operand. If yes, then the condition becomes true. 15>=18 returns false <= Checks if the value of left operand is less than or equal to the value of right operand. If yes, then the condition becomes true. 15<=18 returns true === Identical that means 3===3 returns true !== Is not identical 8!==“8” returns true
  • 10. SMG PHP NOTES 10 Assignment operator The assignment operators are used to assign values result of an expression to a variable assigns values from right side operands to left side operand Operator Description Example = Simple assignment operator. $C = $A + $B will assign the value of $A + $B to $C += Add AND assignment operator. $C+= $A is equivalent to $C = $C + $A -= Subtract AND assignment operator. $C -= $A is equivalent to $C = $C - $A *= Multiply AND assignment operator. $C *= $A is equivalent to $C = $C * $A /= Divide AND assignment operator. $C /= $A is equivalent to $C = $C / $A %= Modulus AND assignment operator. $C %= $A is equivalent to $C = $C % $A Increment and decrement Increment ++ increases the value by 1 whereas decrement -- decreases the value by 1. ++ operator as prefix like: ++$var. The value of var is incremented by 1 then, it returns the value. use ++ operator as postfix like: $var++. The original value of var is returned first then, var is incremented by 1 Bitwise Operator The Bitwise operators is used to perform bit-level operations on the operands. The operators are first converted to bit-level (Binary Digit) and then calculation is performed on the operands. Operator Meaning Bitwise AND & This is a binary operator. Bitwise AND operator in PHP takes two numbers as operands and does AND on every bit of two numbers. The result of AND is 1 only if both bits are 1. Bitwise OR | This is also binary operator. Bitwise OR operator takes two numbers as operands and does OR on every bit of two numbers. The result of OR is 1 any of the two bits is 1. Bitwise XOR ^ This is also binary operator. Bitwise XOR takes two numbers as operands and does XOR on every bit of two numbers. The result of XOR is 1 if the two bits are different.
  • 11. SMG PHP NOTES 11 Numbers/ Bit level 23=8 22=4 21=2 20=1 Result 4 0 1 0 0 5 0 1 0 1 Bitwise AND & 0 1 0 0 4 Bitwise OR | 0 1 0 1 5 Bitwise OR ^ 0 0 0 1 1 Example <?php $a=5; $b=4; $c=$a&$b; $d=$a|$b; $e=$a^$b; echo"BitwiseAND$c"."<br>"; echo"BitwiseOR$d"."<br>"; echo"BitwiseXOR$e"."<br>"; ?> Output Ternary Operator In simple words, PHP Ternary Operator is a shortened method of writing an if-else statement. Syntax $condition ? 'true result' : 'false result'; Example <?php $n=11; $ans=($n%2==0)?"even number":"odd number"; echo $ans; ?>
  • 12. SMG PHP NOTES 12 Output Reference When the = operator is used, PHP performs a copy operation. References allow two variables to refer to the same content. The ampersand (&) is placed before the variable to be referenced. Once two variables are pointing to the same data, either of variables can be changed and the other one will also be updated. Example <?php $a=5; $b=&$a; echo"before update a=$a"."<br>"; echo"before update b=$b"."<br>"; $a++; echo "After update a=$a and b=$b"."<br>"; $b++; echo "now b update a=$a and b=$b"."<br>"; ?>
  • 13. SMG PHP NOTES 13 Output Precedence of PHP Operators Operator precedence determines the grouping of terms in an expression. This affects how an expression is evaluated. For example x = 7 + 3 * 2; Here x is assigned 13, not 20 because operator * has higher precedence than + so it first get multiplied with 3*2 and then adds into 7. Category Operator Associativity Unary ! ++ -- Right to left Multiplicative * / % Left to right Additive + - Left to right Relational < <= > >= Left to right Equality == != Left to right Logical AND && Left to right Logical OR || Left to right Conditional ?: Right to left Assignment = += -= *= /= %= Right to left
  • 14. SMG PHP NOTES 14 Arrays An array is a special variable, which can hold more than one value at a time. Array is differs from normal variable when it’s created and its being accessed. To store array values in an array use square bracket ([ ]). $a[0] = "one"; $a[1] = "two"; $a[2] = "three"; $a[3] = "four"; $a[4] = "five"; Alternatively PHP provides function that allows to create an array. The above data inserted into an array using the function array() as follows: $a=array(0=>”one”,1=>”two”,2=>”three”,3=>”four”,4=>”five”); To access array values as follows echo $a[0]; echo $a[1]; Associate Arrays The associative arrays are very similar to arrays in term of functionality but they are different in terms of their index. Associative array will have their index as string. $student[‘name’]=”Ram”; $student[‘mark’]=40; To access associate array values as follows echo”hi Mr”.$$student[‘name’] . “you got”.$student[‘mark’];
  • 15. SMG PHP NOTES 15 Conditional statements PHP lets programmers evaluate different conditions during of a program and take decisions based on whether these conditions evaluate to true of false. These conditions, and the actions associated with them, are expressed by means of a programming construct called a conditional statement. They are If else The if...else statement allows you to execute one block of code if the specified condition is evaluates to true and another block of code if it is evaluates to false. Syntax if(condition) { true statement; } else { False statement; } Example program <?php $month=date("M");/*Returns a string formatted according to the given format */ if($month=="May") { echo"This month is May"."<br>"; echo"its starting stage of Summer Season"; } else { echo$month; } ?>
  • 16. SMG PHP NOTES 16 Output From the above example current month assigned to the variable $month, then check is made as to whether variable holds value May. If value is May executed true statement, otherwise returns false statement. The elseif clause The if-else-if-else statement lets chain together multiple if-else statements used conduct a serial of conditional checks and only executes the first condition that is met. Syntax if(condition1) { executed if condition1 is true; } elseif(condition2) { executed if the condition1 is false and condition2 is true; } else { executed if both condition1 and condition2 are false; }
  • 17. SMG PHP NOTES 17 Example <?php $month=date("M"); if($month=="Jan") { echo"This month is January"."<br>"; echo"Numeric value is 1"; } elseif($month=="Feb") { echo"This month is February"."<br>"; echo"Numeric value is 2"; } elseif($month=="Mar") { echo"This month is March"."<br>"; echo"Numeric value is 3"; } elseif($month=="Apr") { echo"This month is April"."<br>"; echo"Numeric value is 4"; } elseif($month=="May") { echo"This month is May"."<br>"; echo"Numeric value is 5"; } elseif($month=="Jun") { echo"This month is June"."<br>"; echo"Numeric value is 6"; } else { echo$month; } ?>
  • 18. SMG PHP NOTES 18 Output The above code starts by extracting the month and storing into $month. A check is made if extracted month is January the returns TRUE, executes current statement. If condition is FALSE checks next condition this process continues until either appropriate code block is executed or else clause (FALSE statement). Another method of achieve same functionality using elseif clause <?php $a=5; $b=9; $c=20; if($a>$b&&$a>$c) { print"$a is big"; } else { if ($b>$a&&$b>$c) { print"$b is big"; } else { print"$c is big"; } } ?>
  • 19. SMG PHP NOTES 19 The switch statement The switch-case statement is an alternative to the if-elseif-else statement, which does almost the same thing. The switch-case statement tests a variable against a series of values until it finds a match, and then executes the block of code corresponding to that match. The switch statement is given an expression. This expression compared to all possible expression listed in its body. On successful match, the code block under that particular case expression is executed, after all code spec terminates because of explicit break which mentioned in each case section. Syntax switch(expression) { case label1: //code to be executed break; case label2: //code to be executed break; ...... default: code to be executed if all cases are not matched; } Example <?php $d=date("D"); switch($d) { case "Mon": print"its monday"; echo'<body style="background-color:green">'; break; case "Tue": print"its Tuesday"; echo'<body style="background-color:red">'; break; case "Wed": echo'<body style="background-color:yellow">'; print"its Wednesday"; break; case "Thu": print"its Thursday"; echo'<body style="background-color:#999900">'; break; case "Fri": print"its Friday"; echo'<body style="background-color:blue">'; break; case "Sat": print"its Saturday"; echo'<body style="background-color:ff66ff">';
  • 20. SMG PHP NOTES 20 break; case "Sun": print"its Sunday"; echo'<body style="background-color:orange">'; break; default: print"none of the above"; } ?> Output
  • 21. SMG PHP NOTES 21 Looping Execution of a statement or set of statement repeatedly is called as looping. The loop may be executed a specified number of times and this depends on the satisfaction of a test condition. In PHP the following loop statements are available For- loops through a block of code specified number of times While- loops through a block of code as long as specified condition is TRUE Do..while - loops through a block of code at least once and repeated as long as specified condition is TRUE Foreach- loops through the elements of an array. Works only on arrays. Will throw an error when used with a variable of a different data type or an un-initialized variable. The for loop Loops through a block of code specified number of times. The general structure of for loop for (initialization; test condition; increment) { body of the loop } initialize : Initialize the loop counter value state of variable to be tested, normally done by assignment operator. test condition: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues. If it evaluates to FALSE, the loop ends. increment : Increases the loop counter value When the control enters for loop the variables used in for loop is initialized with the starting value The value which was initialized is then checked with the given test condition. The test condition is a relational expression, such as I < 5 that checks whether the given condition is satisfied or not if the given condition is satisfied the control enters the body of the loop or else it will exit the loop. The body of the loop is entered only if the test condition is satisfied and after the completion of the execution of the loop the control is transferred back to the increment part of the loop. The control variable is incremented using an assignment statement such as I=I+1 or simply I++ and the new value of the control variable is again tested to check whether it satisfies the loop condition. If the value of the control variable satisfies then the body of the loop is again executed. The process goes on till the control variable fails to satisfy the condition
  • 22. SMG PHP NOTES 22 Example <?php for($i=1;$i<=10;$i++) { echo"<b>The value is $i<br/></b>"; } Output
  • 23. SMG PHP NOTES 23 While loop The while loop executes a block of code as long as the specified condition is true. Syntax while (condition is true) { code to be executed; } Here the given test condition is evaluated and if the condition is true then the body of the loop is executed. After the execution of the body, the test condition is once again evaluated and if it is true, the body is executed once again. This process of repeated execution of the body
  • 24. SMG PHP NOTES 24 continues until the test condition finally becomes false and the control is transferred out of the loop. Example <?php $ctr=1; while($ctr<=16) { echo"<b>5X$ctr=</b>".(5*$ctr)."<br/>"; $ctr++; } ?> Output Controlling Array using while Loop Often while loop is used to run through an array as follows while(list($key,$val)=each($array) { echo “ key=> $val”; } Example <?php $array=array(‘Tamilnadu’=>’Chennai’,’Goa’=>’panji’,’Maharashtra’=>’Mumbai’); while($list($key,$value)=each($array)) { echo $key.”<br>”; echo $value. “<br>’; ?> The do...while Loop The do...while loop will always execute the block of code once, it will then check the condition, and repeat the loop while the specified condition is true. Syntax do
  • 25. SMG PHP NOTES 25 { code to be executed; } while (condition is true); Here the statement is executed, then expression is evaluated. If the condition expression is true then the body is executed again and this process continues till the conditional expression becomes false. When the expression becomes false. When the expression becomes false the loop terminates. Example <?php $i=0; do { $i++; echo $i."<br>"; }while($i<10); ?> Output
  • 26. SMG PHP NOTES 26 foreach Loop The foreach loop is used to iterate over arrays. foreach($array as $value) { // Code to be executed; } Example <?php $name=array('Ram','Seetha','Ajay','Kumar','Pari','Karthick');//array creation $n=1; foreach ($name as $value) { echo"The name is in position $n:$value"."<br>"; $n++; } ?> Output 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. 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.
  • 27. SMG PHP NOTES 27 For the pass encountering continue statement, rest of the loop code is skipped and next pass starts.