PHP-NOTES
PHP-NOTES
What is PHP?
PHP is an acronym for "PHP Hypertext Preprocessor"
PHP is a widely-used, open source scripting language
PHP scripts are executed on the server
PHP costs nothing, it is free to download and use
Why PHP?
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
PHP is a server scripting language, and is a powerful tool for making dynamic and
interactive Web pages quickly.
1
SANDEEP SHARMA (PHP-NOTES)
<!DOCTYPE html>
<html>
<body>
<?php
echo "My first PHP script!";
?>
</body>
</html>
<?php
// PHP code goes here
?>
A PHP file normally contains HTML tags, and some PHP scripting code.
Below, we have an example of a simple PHP file, with a PHP script that uses a built-in
PHP function "echo" to output the text "Hello World!" on a web page:
Example
<!DOCTYPE html>
<html>
<body>
<h1>My first PHP page</h1>
<?php
echo "Hello World!";
?>
</body>
</html>
2
SANDEEP SHARMA (PHP-NOTES)
Note: PHP statements are terminated by semicolon (;). The closing tag of a block of
PHP code also automatically implies a semicolon (so you do not have to have a
semicolon terminating the last line of a PHP block).
Comments in PHP
A comment in PHP code is a line that is not read/executed as part of the program. Its
only purpose is to be read by someone who is editing the code!
To let others understand what you are doing - Comments let other programmers
understand what you were doing in each step (if you work in a group)
To remind yourself what you did - Most programmers have experienced coming
back to their own work a year or two later and having to re-figure out what they
did. Comments can remind you of what you were thinking when you wrote the
code
Example
<!DOCTYPE html>
<html>
<body>
<?php
// This is a single line comment
# This is also a single line comment
/*
This is a multiple lines comment block
that spans over more than
one line
*/
?>
</body>
</html>
In the example below, all three echo statements below are legal (and equal):
Example
<!DOCTYPE html>
<html>
<body>
<?php
ECHO "Hello World!<br>";
echo "Hello World!<br>";
EcHo "Hello World!<br>";
?>
</body>
</html>
In the example below, only the first statement will display the value of the $color
variable (this is because $color, $COLOR, and $coLOR are treated as three different
variables):
<!DOCTYPE html>
<html>
<body>
<?php
$color="red";
echo "My car is " . $color . "<br>";
echo "My house is " . $COLOR . "<br>";
echo "My boat is " . $coLOR . "<br>";
?>
</body>
</html>
PHP Variables
4
SANDEEP SHARMA (PHP-NOTES)
As with algebra, PHP variables can be used to hold values (x=5) or expressions (z=x+y).
A variable can have a short name (like x and y) or a more descriptive name (age,
carname, total_volume).
A variable starts with the $ 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 ($y and $Y are two different variables)
A variable declared within a function has a LOCAL SCOPE and can only be accessed
within that function.
The following example tests variables with local and global scope:
Example
<?php
$x=5; // global scope
5
SANDEEP SHARMA (PHP-NOTES)
function myTest()
{
$y=10; // local scope
echo "<p>Test variables inside the function:<p>";
echo "Variable x is: $x";
echo "<br>";
echo "Variable y is: $y";
}
myTest();
echo "<p>Test variables outside the function:<p>";
echo "Variable x is: $x";
echo "<br>";
echo "Variable y is: $y";
?>
To do this, use the global keyword before the variables (inside the function):
Example
<?php
$x=5;
$y=10;
function myTest()
{
global $x,$y;
$y=$x+$y;
}
myTest();
echo $y; // outputs 15
?>
PHP also stores all global variables in an array called $GLOBALS[index]. The index holds
the name of the variable. This array is also accessible from within functions and can be
used to update global variables directly.
6
SANDEEP SHARMA (PHP-NOTES)
Example
<?php
$x=5;
$y=10;
function myTest()
{
$GLOBALS['y']=$GLOBALS['x']+$GLOBALS['y'];
}
myTest();
echo $y; // outputs 15
?>
To do this, use the static keyword when you first declare the variable:
Example
<?php
function myTest()
{
static $x=0;
echo $x;
$x++;
}
myTest();
myTest();
myTest();
?>
In PHP there is two basic ways to get output: echo and print.
7
SANDEEP SHARMA (PHP-NOTES)
In this tutorial we use echo (and print) in almost every example. So, this chapter
contains a little more info about those two output statements.
Tip: echo is marginally faster compared to print as echo does not return any value.
Display Strings
The following example shows how to display different strings with the echo command
(also notice that the strings can contain HTML markup):
Example
<?php
echo "<h2>PHP is fun!</h2>";
echo "Hello world!<br>";
echo "I'm about to learn PHP!<br>";
echo "This", " string", " was", " made", " with multiple parameters.";
?>
Display Variables
The following example shows how to display strings and variables with the echo
command:
Example
<?php
$txt1="Learn PHP";
8
SANDEEP SHARMA (PHP-NOTES)
$txt2="W3Schools.com";
$cars=array("Volvo","BMW","Toyota");
echo $txt1;
echo "<br>";
echo "Study PHP at $txt2";
echo "My car is a {$cars[0]}";
?>
Display Strings
The following example shows how to display different strings with the print command
(also notice that the strings can contain HTML markup):
Example
<?php
print "<h2>PHP is fun!</h2>";
print "Hello world!<br>";
print "I'm about to learn PHP!";
?>
Display Variables
The following example shows how to display strings and variables with the print
command:
Example
<?php
$txt1="Learn PHP";
$txt2="W3Schools.com";
$cars=array("Volvo","BMW","Toyota");
print $txt1;
print "<br>";
9
SANDEEP SHARMA (PHP-NOTES)
PHP Strings
A string is a sequence of characters, like "Hello world!".A string can be any text inside
quotes. You can use single or double quotes:
Example
<?php
$x = "Hello world!";
echo $x;
echo "<br>";
$x = 'Hello world!';
echo $x;
?>
PHP Integers
An integer is a number without decimals.
In the following example we will test different numbers. The PHP var_dump() function
returns the data type and value of variables:
Example
<?php
$x = 5985;
var_dump($x);
echo "<br>";
$x = -345; // negative number
var_dump($x);
echo "<br>";
$x = 0x8C; // hexadecimal number
var_dump($x);
echo "<br>";
$x = 047; // octal number
var_dump($x);
?>
In the following example we will test different numbers. The PHP var_dump() function
returns the data type and value of variables:
Example
<?php
$x = 10.365;
var_dump($x);
echo "<br>";
$x = 2.4e3;
var_dump($x);
echo "<br>";
11
SANDEEP SHARMA (PHP-NOTES)
$x = 8E-5;
var_dump($x);
?>
PHP Booleans
Booleans can be either TRUE or FALSE.
$x=true;
$y=false;
Booleans are often used in conditional testing. You will learn more about conditional
testing in a later chapter of this tutorial.
PHP Arrays
An array stores multiple values in one single variable.
In the following example we create an array, and then use the PHP var_dump() function
to return the data type and value of the array:
Example
<!DOCTYPE html>
<html>
<body>
<?php
$cars=array("Volvo","BMW","Toyota");
var_dump($cars);
?>
</body>
</html>
PHP Objects
12
SANDEEP SHARMA (PHP-NOTES)
An object is a data type which stores data and information on how to process that data.
First we must declare a class of object. For this, we use the class keyword. A class is a
structure that can contain properties and methods.
We then define the data type in the object class, and then we use the data type in
instances of that class:
The NULL value identifies whether a variable is empty or not. Also useful to differentiate
between the empty string and null values of databases.
<!DOCTYPE html>
<html>
<body>
<?php
$x="Hello world!";
$x=null;
var_dump($x);
?>
</body>
</html>
13
SANDEEP SHARMA (PHP-NOTES)
In this chapter we will look at some commonly used functions to manipulate strings.
The example below returns the length of the string "Hello world!":
<!DOCTYPE html>
<html>
<body>
<?php
echo strlen("Hello world!");
?>
</body>
</html>
If a match is found, it will return the character position of the first match. If no match is
found, it will return FALSE.
The example below searches for the text "world" in the string "Hello world!":
<!DOCTYPE html>
<html>
<body>
<?php
echo strpos("Hello world!","world");
?>
</body>
</html>
14
SANDEEP SHARMA (PHP-NOTES)
PHP Constants
Constants are like variables except that once they are defined they cannot be
changed or undefined.
PHP Constants
A constant is an identifier (name) for a simple value. The value cannot be changed
during the script.
A valid constant name starts with a letter or underscore (no $ sign before the constant
name).
Note: Unlike variables, constants are automatically global across the entire script .
<!DOCTYPE html>
<html>
<body>
<?php
// define a case-sensitive constant
define("GREETING", "Welcome to W3Schools.com!");
echo GREETING;
echo "<br>";
// will not output the value of the constant
echo greeting;
?>
</body>
</html>
15
SANDEEP SHARMA (PHP-NOTES)
<!DOCTYPE html>
<html>
<body>
<?php
// define a case-insensitive constant
define("GREETING", "Welcome to W3Schools.com!", true);
echo GREETING;
echo "<br>";
// will also output the value of the constant
echo greeting;
?>
</body>
</html>
The basic assignment operator in PHP is "=". It means that the left operand gets set to
the value of the assignment expression on the right.
16
SANDEEP SHARMA (PHP-NOTES)
x=y x=y The left operand gets set to the value of the expression on the right
x += y x=x+y Addition
x -= y x=x-y Subtraction
x *= y x=x*y Multiplication
x /= y x=x/y Division
x %= y x=x%y Modulus
=== Identical $x === $y True if $x is equal to $y, and they are of the
17
SANDEEP SHARMA (PHP-NOTES)
!== Not identical $x !== $y True if $x is not equal to $y, or they are not
type
18
SANDEEP SHARMA (PHP-NOTES)
=== Identity $x === $y True if $x and $y have the same key/value pairs in the sa
and of the same types
19
SANDEEP SHARMA (PHP-NOTES)
20
SANDEEP SHARMA (PHP-NOTES)
Syntax
if (condition)
{
code to be executed if condition is true;
}
<!DOCTYPE html>
<html>
<body>
<?php
$t=date("H");
if ($t<"20")
{
echo "Have a good day!";
}
?>
21
SANDEEP SHARMA (PHP-NOTES)
</body>
</html>
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;
}
<!DOCTYPE html>
<html>
<body>
<?php
$t=date("H");
if ($t<"10")
{
echo "Have a good morning!";
}
elseif ($t<"20")
{
echo "Have a good day!";
}
else
22
SANDEEP SHARMA (PHP-NOTES)
{
echo "Have a good night!";
}
?>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<?php
$favcolor="red";
switch ($favcolor)
{
case "red":
echo "Your favorite color is red!";
break;
case "blue":
echo "Your favorite color is blue!";
break;
case "green":
echo "Your favorite color is green!";
break;
default:
echo "Your favorite color is neither red, blue, or green!";
}
23
SANDEEP SHARMA (PHP-NOTES)
?>
</body>
</html>
PHP Loops
Often when you write code, you want the same block of code to run over and over again
in a row. Instead of adding several almost equal code-lines in a script, we can use loops
to perform a task like this.
while - loops through a block of code as long as the specified condition is true
do...while - loops through a block of code once, and then repeats the loop as
long as the specified condition is true
for - loops through a block of code a specified number of times
foreach - loops through a block of code for each element in an array
<!DOCTYPE html>
<html>
<body>
<?php
$x=1;
while($x<=5)
{
echo "The number is: $x <br>";
$x++;
}
?>
</body>
</html>
24
SANDEEP SHARMA (PHP-NOTES)
<!DOCTYPE html>
<html>
<body>
<?php
$x=1;
do
{
echo "The number is: $x <br>";
$x++;
}
while ($x<=5)
?>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<?php
for ($x=0; $x<=10; $x++)
{
echo "The number is: $x <br>";
}
?>
</body>
</html>
25
SANDEEP SHARMA (PHP-NOTES)
<!DOCTYPE html>
<html>
<body>
<?php
$colors = array("red","green","blue","yellow");
foreach ($colors as $value)
{
echo "$value <br>";
}
?>
</body>
</html>
PHP Functions
PHP User Defined Functions
Besides the built-in PHP functions, we can create our own functions.
26
SANDEEP SHARMA (PHP-NOTES)
<!DOCTYPE html>
<html>
<body>
<?php
function writeMsg()
{
echo "Hello world!";
}
writeMsg();
?>
</body>
</html>
Arguments are specified after the function name, inside the parentheses. You can
add as many arguments as you want, just seperate them with a comma.
The following example has a function with one argument ($fname). When the
familyName() function is called, we also pass along a name (e.g. Jani), and the
name is used inside the function, which outputs several different first names, but an
equal last name:
<!DOCTYPE html>
<html>
<body>
<?php
function familyName($fname)
{
echo "$fname Refsnes.<br>";
}
familyName("Jani");
familyName("Hege");
familyName("Stale");
familyName("Kai Jim");
familyName("Borge");
27
SANDEEP SHARMA (PHP-NOTES)
?>
</body>
</html>
28