What Is PHP
What Is PHP
With PHP you are not limited to output HTML. You can output images, PDF files,
and even Flash movies. You can also output any text, such as XHTML and XML.
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 Installation
What Do I Need?
To start using PHP, you can:
Just create some .php files, place them in your web directory, and the server will
automatically parse them for you.
A PHP script is executed on the server, and the plain HTML result is sent
back to the browser.
<?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>
<?php
echo "Hello World!";
?>
</body>
</html>
In the example below, all three echo statements below are equal and legal:
Example
<!DOCTYPE html>
<html>
<body>
<?php
ECHO "Hello World!<br>";
echo "Hello World!<br>";
EcHo "Hello World!<br>";
?>
</body>
</html>
Look at 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:
Example
<!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>
Comments in PHP
A comment in PHP code is a line that is not executed as a part of the program.
Its only purpose is to be read by someone who is looking at the code.
Example
Syntax for single-line comments:
<!DOCTYPE html>
<html>
<body>
<?php
// This is a single-line comment
</body>
</html>
Example
Syntax for multiple-line comments:
<!DOCTYPE html>
<html>
<body>
<?php
/*
This is a multiple-lines comment block
that spans over multiple
lines
*/
?>
</body>
</html>
Example
Using comments to leave out parts of the code:
<!DOCTYPE html>
<html>
<body>
<?php
// You can also use comments to leave out parts of a code line
$x = 5 /* + 15 */ + 5;
echo $x;
?>
</body>
</html>
PHP Variables
Variables are "containers" for storing information.
Creating (Declaring) PHP Variables
In PHP, a variable starts with the $ sign, followed by the name of the variable:
Example
<?php
$txt = "Hello world!";
$x = 5;
$y = 10.5;
?>
After the execution of the statements above, the variable $txt will hold the
value Hello world!, the variable $x will hold the value 5, and the
variable $y will hold the value 10.5.
Note: When you assign a text value to a variable, put quotes around the value.
Note: Unlike other programming languages, PHP has no command for declaring
a variable. It is created the moment you first assign a value to it.
PHP Variables
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 ($age and $AGE are two different
variables)
The following example will show how to output text and a variable:
Example
<?php
$txt = "W3Schools.com";
echo "I love $txt!";
?>
The following example will produce the same output as the example above:
Example
<?php
$txt = "W3Schools.com";
echo "I love " . $txt . "!";
?>
Example
<?php
$x = 5;
$y = 4;
echo $x + $y;
?>
You will learn more about strict and non-strict requirements, and data type
declarations in the PHP Functions chapter.
The scope of a variable is the part of the script where the variable can be
referenced/used.
local
global
static
Example
Variable with global scope:
<?php
$x = 5; // global scope
function myTest() {
// using x inside this function will generate an error
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
echo "<p>Variable x outside function is: $x</p>";
?>
A variable declared within a function has a LOCAL SCOPE and can only be
accessed within that function:
Example
Variable with local scope:
<?php
function myTest() {
$x = 5; // local scope
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
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.
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();
?>
Then, each time the function is called, that variable will still have the
information it contained from the last time the function was called.
String
Integer
Float (floating point numbers - also called double)
Boolean
Array
Object
NULL
Resource
PHP String
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!";
$y = 'Hello world!';
echo $x;
echo "<br>";
echo $y;
?>
PHP Integer
An integer data type is a non-decimal number between -2,147,483,648 and
2,147,483,647.
Example
<?php
$x = 5985;
var_dump($x);
?>
PHP Float
A float (floating point number) is a number with a decimal point or a number in
exponential form.
In the following example $x is a float. The PHP var_dump() function returns the
data type and value:
Example
<?php
$x = 10.365;
var_dump($x);
?>
PHP Boolean
A Boolean represents two possible states: 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 Array
An array stores multiple values in one single variable.
Example
<?php
$cars = array("Volvo","BMW","Toyota");
var_dump($cars);
?>
You will learn a lot more about arrays in later chapters of this tutorial.
PHP Object
Classes and objects are the two main aspects of object-oriented programming.
When the individual objects are created, they inherit all the properties and
behaviors from the class, but each object will have different values for the
properties.
Let's assume we have a class named Car. A Car can have properties like model,
color, etc. We can define variables like $model, $color, and so on, to hold the
values of these properties.
When the individual objects (Volvo, BMW, Toyota, etc.) are created, they inherit
all the properties and behaviors from the class, but each object will have
different values for the properties.
If you create a __construct() function, PHP will automatically call this function
when you create an object from a class.
Example
<?php
class Car {
public $color;
public $model;
public function __construct($color, $model) {
$this->color = $color;
$this->model = $model;
}
public function message() {
return "My car is a " . $this->color . " " . $this->model . "!";
}
}
A variable of data type NULL is a variable that has no value assigned to it.
Example
<?php
$x = "Hello world!";
$x = null;
var_dump($x);
?>
PHP Resource
The special resource type is not an actual data type. It is the storing of a
reference to functions and resources external to PHP.
<?php
$a = "32"; // string
settype($a, "integer"); // $a is now integer
$b = 32; // integer
settype($b, "string"); // $b is now string
$c = true; // boolean
settype($c, "integer"); // $c is now integer (1)
?>
Syntax
settype(variable, type);
Parameter Values
Parameter Description
boolean, bool, integer, int, float, double, string, array, object, null
PHP Operators
Operators are used to perform operations on variables and values.
Arithmetic operators
Assignment operators
Comparison operators
Increment/Decrement operators
Logical operators
String operators
Array operators
Conditional assignment operators
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
The PHP assignment operators are used with numeric values to write a value to
a variable.
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.
=== Identical $x === Returns true if $x is equal to $y, and they are of
$y the same type
!== Not $x !== Returns true if $x is not equal to $y, or they are
identical $y not of the same type
<=> Spaceship $x <=> Returns an integer less than, equal to, or greater
$y than zero, depending on if $x is less than, equal
to, or greater than $y. Introduced in PHP 7.
PHP Increment / Decrement Operators
Operator Name Description
Syntax
if (condition) {
code to be executed if condition is true;
}Example
Output "Have a good day!" if the current time (HOUR) is less than 20:
<?php
$t = date("H");
Syntax
if (condition) {
code to be executed if condition is true;
} else {
code to be executed if condition is false;
}
Example
Output "Have a good day!" if the current time is less than 20, and "Have a good
night!" otherwise:
<?php
$t = date("H");
Syntax
if (condition) {
code to be executed if this condition is true;
} elseif (condition) {
code to be executed if first condition is false and this condition is
true;
} else {
code to be executed if all conditions are false;
}
Example
Output "Have a good morning!" if the current time is less than 10, and "Have a
good day!" if the current time is less than 20. Otherwise it will output "Have a
good night!":
<?php
$t = date("H");
Example
<?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, nor green!";
}
?>
The PHP 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;
}
Examples
The example below displays the numbers from 1 to 5:
<?php
$x = 1;
while($x <= 5) {
echo "The number is: $x <br>";
$x++;
}
?>
Example Explained
$x = 1; - Initialize the loop counter ($x), and set the start value to 1
$x <= 5 - Continue the loop as long as $x is less than or equal to 5
$x++; - Increase the loop counter value by 1 for each iteration
Example
<?php
$x = 0;
Example Explained
$x = 0; - Initialize the loop counter ($x), and set the start value to 0
$x <= 100 - Continue the loop as long as $x is less than or equal to 100
$x+=10; - Increase the loop counter value by 10 for each iteration
Examples
The example below first sets a variable $x to 1 ($x = 1). Then, the do while
loop will write some output, and then increment the variable $x with 1. Then
the condition is checked (is $x less than, or equal to 5?), and the loop will
continue to run as long as $x is less than, or equal to 5:
Example
<?php
$x = 1;
do {
echo "The number is: $x <br>";
$x++;
} while ($x <= 5);
?>
This example sets the $x variable to 6, then it runs the loop, and then the
condition is checked:
Example
<?php
$x = 6;
do {
echo "The number is: $x <br>";
$x++;
} while ($x <= 5);
?>
The PHP for Loop
The for loop is used when you know in advance how many times the script
should run.
Syntax
for (init counter; test counter; increment counter) {
code to be executed for each iteration;
}
Parameters:
Examples
The example below displays the numbers from 0 to 10:
Example
<?php
for ($x = 0; $x <= 10; $x++) {
echo "The number is: $x <br>";
}
?>
Example Explained
$x = 0; - Initialize the loop counter ($x), and set the start value to 0
$x <= 10; - Continue the loop as long as $x is less than or equal to 10
$x++ - Increase the loop counter value by 1 for each iteration
Example
<?php
for ($x = 0; $x <= 100; $x+=10) {
echo "The number is: $x <br>";
}
?>
Example Explained
$x = 0; - Initialize the loop counter ($x), and set the start value to 0
$x <= 100; - Continue the loop as long as $x is less than or equal to 100
$x+=10 - Increase the loop counter value by 10 for each iteration
Syntax
foreach ($array as $value) {
code to be executed;
}
For every loop iteration, the value of the current array element is assigned to
$value and the array pointer is moved by one, until it reaches the last array
element.
Examples
The following example will output the values of the given array ($colors):
Example
<?php
$colors = array("red", "green", "blue", "yellow");
The following example will output both the keys and the values of the given
array ($age):
Example
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
PHP Break
You have already seen the break statement used in an earlier chapter of this
tutorial. It was used to "jump out" of a switch statement.
Example
<?php
for ($x = 0; $x < 10; $x++) {
if ($x == 4) {
break;
}
echo "The number is: $x <br>";
}
?>
PHP Continue
The continue statement breaks one iteration (in the loop), if a specified condition
occurs, and continues with the next iteration in the loop.
Example
<?php
for ($x = 0; $x < 10; $x++) {
if ($x == 4) {
continue;
}
echo "The number is: $x <br>";
}
?>
Break Example
<?php
$x = 0;
Continue Example
<?php
$x = 0;
Php Script
PHP is a server side scripting language. That is used to
develop Static websites or Dynamic websites or Web
applications. PHP stands for Hypertext Pre-processor, that
earlier stood for Personal Home Pages. PHP scripts can
only be interpreted on a server that has PHP installed.
1. Client-side scripting :
Web browsers execute client-side scripting. It is used when browsers have all
code. Source code is used to transfer from webserver to user’s computer over
the internet and run directly on browsers. It is also used for validations and
functionality for user events.
It allows for more interactivity. It usually performs several actions without going
to the user. It cannot be basically used to connect to databases on a web
server. These scripts cannot access the file system that resides in the web
browser. Pages are altered on basis of the user’s choice. It can also be used to
create “cookies” that store data on the user’s computer.
2. Server-side scripting :
Web servers are used to execute server-side scripting. They are basically used
to create dynamic pages. It can also access the file system residing at the
webserver. A server-side environment that runs on a scripting language is a
web server.
Scripts can be written in any of a number of server-side scripting languages
available. It is used to retrieve and generate content for dynamic pages. It is
used to require to download plugins. In this load times are generally faster than
client-side scripting. When you need to store and retrieve information a
database will be used to contain data. It can use huge resources of the server.
It reduces client-side computation overhead. The server sends pages to the
request of the user/client.
It does not provide security for data. It provides more security for data.
HTML, CSS, and javascript are used. PHP, Python, Java, Ruby are used.
2. These are made for a particular Programming languages are of three types
-:
low-level Programming language
Middle-level Programming language
High-level Programming language
runtime environment.
They are used to create dynamic Programming languages are used to write
3. web applications computer programs.
Most of the scripting languages are Most of the programming languages are
9. interpreted language. compiled languages.
All the scripting languages are All the programming languages are not
10. programming languages. scripting languages.
PHP Server
The PHP Community Provides Some types of Software Server solution under The GNU
(General Public License).
These are the following:
1. WAMP Server
2. LAMP Server
3. MAMP Server
4. XAMPP Server
All these types of software automatic configure inside operating system after installation
it having PHP, MySQL, Apache and operating system base configuration file, it doesn't
need to configure manually.
PHP Functions
The real power of PHP comes from its functions.
PHP has more than 1000 built-in functions, and in addition you can create
your own custom functions.
Syntax
function functionName() {
code to be executed;
}
Tip: Give the function a name that reflects what the function does!
Example
<?php
function writeMsg() {
echo "Hello world!";
}
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.
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:
Example
<?php
function familyName($fname) {
echo "$fname Refsnes.<br>";
}
familyName("Jani");
familyName("Hege");
familyName("Stale");
familyName("Kai Jim");
familyName("Borge");
?>
The following example has a function with two arguments ($fname and $year):
Example
<?php
function familyName($fname, $year) {
echo "$fname Refsnes. Born in $year <br>";
}
familyName("Hege", "1975");
familyName("Stale", "1978");
familyName("Kai Jim", "1983");
?>
In PHP 7, type declarations were added. This gives us an option to specify the
expected data type when declaring a function, and by adding
the strict declaration, it will throw a "Fatal Error" if the data type mismatches.
In the following example we try to send both a number and a string to the
function without using strict:
Example
<?php
function addNumbers(int $a, int $b) {
return $a + $b;
}
echo addNumbers(5, "5 days");
// since strict is NOT enabled "5 days" is changed to int(5), and it will
return 10
?>
In the following example we try to send both a number and a string to the
function, but here we have added the strict declaration:
Example
<?php declare(strict_types=1); // strict requirement
Example
<?php declare(strict_types=1); // strict requirement
function setHeight(int $minheight = 50) {
echo "The height is : $minheight <br>";
}
setHeight(350);
setHeight(); // will use the default value of 50
setHeight(135);
setHeight(80);
?>
Example
<?php declare(strict_types=1); // strict requirement
function sum(int $x, int $y) {
$z = $x + $y;
return $z;
}
To declare a type for the function return, add a colon ( : ) and the type right
before the opening curly ( { )bracket when declaring the function.
In the following example we specify the return type for the function:
Example
<?php declare(strict_types=1); // strict requirement
function addNumbers(float $a, float $b) : float {
return $a + $b;
}
echo addNumbers(1.2, 5.2);
?>
You can specify a different return type, than the argument types, but make sure
the return is the correct type:
Example
<?php declare(strict_types=1); // strict requirement
function addNumbers(float $a, float $b) : int {
return (int)($a + $b);
}
echo addNumbers(1.2, 5.2);
?>
Example
Use a pass-by-reference argument to update a variable:
<?php
function add_five(&$value) {
$value += 5;
}
$num = 2;
add_five($num);
echo $num;
?>
PHP Arrays
An array stores multiple values in one single variable:
Example
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>
What is an Array?
An array is a special variable, which can hold more than one value at a time.
If you have a list of items (a list of car names, for example), storing the cars in
single variables could look like this:
$cars1 = "Volvo";
$cars2 = "BMW";
$cars3 = "Toyota";
However, what if you want to loop through the cars and find a specific one? And
what if you had not 3 cars, but 300?
An array can hold many values under a single name, and you can access the
values by referring to an index number.
array();
Example
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo count($cars);
?>
Complete PHP Array Reference
For a complete reference of all array functions, go to our complete PHP Array
Reference.
The reference contains a brief description, and examples of use, for each
function!
The index can be assigned automatically (index always starts at 0), like this:
$cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota";
The following example creates an indexed array named $cars, assigns three
elements to it, and then prints a text containing the array values:
Example
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>
The reference contains a brief description, and examples of use, for each
function!
or:
$age['Peter'] = "35";
$age['Ben'] = "37";
$age['Joe'] = "43";
Example
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
echo "Peter is " . $age['Peter'] . " years old.";
?>
Loop Through an Associative Array
To loop through and print all the values of an associative array, you could use
a foreach loop, like this:
Example
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
The reference contains a brief description, and examples of use, for each
function!
However, sometimes you want to store values with more than one key. For
this, we have multidimensional 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.
The dimension of an array indicates the number of indices you need to
select an element.
Volvo 22 18
BMW 15 13
Saab 5 2
Land Rover 17 15
We can store the data from the table above in a two-dimensional array, like
this:
$cars = array (
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);
Now the two-dimensional $cars array contains four arrays, and it has two
indices: row and column.
To get access to the elements of the $cars array we must point to the two
indices (row and column):
Example
<?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>";
?>
We can also put a for loop inside another for loop to get the elements of the
$cars array (we still have to point to the two indices):
Example
<?php
for ($row = 0; $row < 4; $row++) {
echo "<p><b>Row number $row</b></p>";
echo "<ul>";
for ($col = 0; $col < 3; $col++) {
echo "<li>".$cars[$row][$col]."</li>";
}
echo "</ul>";
}
?>
The reference contains a brief description, and examples of use, for each
function!
PHP Sorting Arrays
The elements in an array can be sorted in alphabetical or numerical order,
descending or ascending.
Example
<?php
$cars = array("Volvo", "BMW", "Toyota");
sort($cars);
?>
The following example sorts the elements of the $numbers array in ascending
numerical order:
Example
<?php
$numbers = array(4, 6, 2, 22, 11);
sort($numbers);
?>
Example
<?php
$cars = array("Volvo", "BMW", "Toyota");
rsort($cars);
?>
The following example sorts the elements of the $numbers array in descending
numerical order:
Example
<?php
$numbers = array(4, 6, 2, 22, 11);
rsort($numbers);
?>
Example
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
asort($age);
?>
Sort Array (Ascending Order), According
to Key - ksort()
The following example sorts an associative array in ascending order, according
to the key:
Example
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
ksort($age);
?>
Example
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
arsort($age);
?>
Example
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
krsort($age);
?>
Complete PHP Array Reference
For a complete reference of all array functions, go to our complete PHP Array
Reference.
The reference contains a brief description, and examples of use, for each
function!
PHP Strings
A string is a sequence of characters, like "Hello world!".
Example
Return the length of the string "Hello world!":
<?php
echo strlen("Hello world!"); // outputs 12
?>
Example
Count the number of word in the string "Hello world!":
<?php
echo str_word_count("Hello world!"); // outputs 2
?>
Example
Reverse the string "Hello world!":
<?php
echo strrev("Hello world!"); // outputs !dlrow olleH
?>
Example
Search for the text "world" in the string "Hello world!":
<?php
echo strpos("Hello world!", "world"); // outputs 6
?>
Example
Replace the text "world" with "Dolly":
<?php
echo str_replace("world", "Dolly", "Hello world!"); // outputs Hello
Dolly!
?>
join() Function
• The join() function is built-in function in PHP and is used to join an array of elements which are
separated by a string.
Syntax