PHP W3schools Tutorial
PHP W3schools Tutorial
HTML
CSS
If you want to study these subjects first, find the tutorials on our Home page.
What is PHP?
PHP files can contain text, HTML, JavaScript code, and PHP code
PHP code are executed on the server, and the result is returned to the
browser as plain HTML
PHP can create, open, read, write, and close files on the server
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 is compatible with almost all servers used today (Apache, IIS, etc.)
PHP Installation
What Do I Need?
To start using PHP, you can:
Install a web server on your own PC, and then install PHP and MySQL
install PHP
The official PHP website (PHP.net) has installation instructions for PHP:
http://php.net/manual/en/install.php
PHP Syntax
The PHP script is executed on the server, and the plain HTML result is sent back to the browser.
Example
<!DOCTYPE html>
<html>
<body>
<h1>My first PHP page</h1>
<?php
echo "Hello World!";
?>
</body>
</html>
Run example
Each code line in PHP must end with a semicolon. The semicolon is a separator and is used to
distinguish one set of instructions from another.
With PHP, there are two basic statements to output text in the browser: echo and print.
Comments in PHP
Example
<!DOCTYPE html>
<html>
<body>
<?php
//This is a PHP comment line
/*
This is
a PHP comment
block
*/
?>
</body>
</html>
Run example
PHP Variables
Example
<?php
$x=5;
$y=6;
$z=$x+$y;
echo $z;
?>
Run example
PHP Variables
As with algebra, PHP variables can be used to hold values (x=5) or expressions (z=x+y).
Variable can have short names (like x and y) or more descriptive names (age, carname,
totalvolume).
Rules for PHP variables:
A variable starts with the $ sign, followed by the name of the variable
Variable names are case sensitive ($y and $Y are two different variables)
Both PHP statements and PHP variables are case-sensitive.
After the execution of the statements above, the variable txt will hold the value Hello world!,
and the variable x will hold the value 5.
Note: When you assign a text value to a variable, put quotes around the value.
local
global
static
parameter
Local Scope
A variable declared within a PHP function is local and can only be accessed within that function:
Example
<?php
$x=5; // global scope
function myTest()
{
echo $x; // local scope
}
myTest();
?>
Run example
The script above will not produce any output because the echo statement refers to the local scope
variable $x, which has not been assigned a value within this scope.
You can have local variables with the same name in different functions, because local variables
are only recognized by the function in which they are declared.
Local variables are deleted as soon as the function is completed.
Global Scope
A variable that is defined outside of any function, has a global scope.
Global variables can be accessed from any part of the script, EXCEPT from within a function.
To access a global variable from within a function, use the global keyword:
Example
<?php
$x=5; // global scope
$y=10; // global scope
function myTest()
{
global $x,$y;
$y=$x+$y;
}
myTest();
echo $y; // outputs 15
?>
Run example
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.
The example above can be rewritten like this:
Example
<?php
$x=5;
$y=10;
function myTest()
{
$GLOBALS['y']=$GLOBALS['x']+$GLOBALS['y'];
}
myTest();
echo $y;
?>
Run example
Static Scope
When a function is completed, all of its variables are normally deleted. However, sometimes you
want a local variable to not be deleted.
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();
?>
Run example
Then, each time the function is called, that variable will still have the information it contained
from the last time the function was called.
Note: The variable is still local to the function.
Parameter Scope
A parameter is a local variable whose value is passed to the function by the calling code.
Parameters are declared in a parameter list as part of the function declaration:
Example
<?php
function myTest($x)
{
echo $x;
}
myTest(5);
?>
Run example
Parameters are also called arguments. We will discuss it in more details in our PHP functions
chapter.
Example
<?php
$txt="Hello world!";
echo $txt;
?>
Run example
Note: When you assign a text value to a variable, remember to put single or
double quotes around the value.
Now, lets look at some commonly used functions and operators to manipulate strings.
Example
<?php
$txt1="Hello world!";
$txt2="What a nice day!";
The output of the code above will be: Hello world! What a nice day!
Tip: In the code above we have used the concatenation operator two times. This is because we
wanted to insert a white space between the two strings.
Example
<?php
echo strlen("Hello world!");
?>
Run example
Example
<?php
echo strpos("Hello world!","world");
?>
Run example
Description
Example
Result
x+y
Addition
Sum of x and y
2+2
x-y
Subtraction
Difference of x and y
5-2
x*y
Multiplication
Product of x and y
5*2
10
x/y
Division
Quotient of x and y
15 / 5
x%y
Modulus
Remainder of x divided
by y
5%2
10 % 8
10 % 2
1
2
0
-x
Negation
Opposite of x
-2
a.b
Concatenation
HiHa
Description
x=y
x=y
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
a .= b
a=a.b
Description
++ x
Pre-increment
x ++
Post-increment
-- x
Pre-decrement
x --
Description
Example
x == y
Equal
True if x is equal to y
x === y
Identical
x != y
Not equal
x <> y
Not equal
x !== y
Not identical
x>y
Greater than
x<y
Less than
x >= y
x <= y
Less than or
equal to
x and y
x or y
x xor y
x && y
Description
Example
x=6
y=3
(x < 10 and y > 1)
returns true
Or
x=6
y=3
(x==6 or y==5) returns
true
Xor
x=6
True if either x or y is true, but y=3
not both
(x==6 xor y==3)
returns false
And
x=6
y=3
(x < 10 && y > 1)
returns true
And
x || y
Or
x=6
y=3
(x==5 || y==5) returns
false
!x
Not
x=6 y=3
!(x==y) returns true
Description
x+y
Union
Union of x and y
x == y
Equality
x === y
Identity
Inequality
x <> y
Inequality
x !== y
Non-identity
Conditional statements are used to perform different actions based on different conditions.
The example below will output "Have a good day!" if the current time is less than 20:
Example
<?php
$t=date("H");
if ($t<"20")
{
echo "Have a good day!";
}
?>
Run example
The example below will output "Have a good day!" if the current time is less than 20, and "Have
a good night!" otherwise:
Example
<?php
$t=date("H");
if ($t<"20")
{
echo "Have a good day!";
}
else
{
echo "Have a good night!";
}
?>
Run example
The example below will 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!":
Example
<?php
$t=date("H");
if ($t<"10")
{
echo "Have a good morning!";
}
else if ($t<"20")
{
echo "Have a good day!";
}
else
{
echo "Have a good night!";
}
?>
Run example
The switch statement is used to perform different actions based on different conditions.
This is how it works: First we have a single expression n (most often a variable), that is
evaluated once. The value of the expression is then compared with the values for each case in the
structure. If there is a match, the block of code associated with that case is executed. Use break
to prevent the code from running into the next case automatically. The default statement is used
if no match is found.
Example
<?php
$favcolor="red";
switch ($favcolor)
{
case "red":
echo "Your favorite
break;
case "blue":
echo "Your favorite
break;
case "green":
echo "Your favorite
break;
default:
echo "Your favorite
}
color is red!";
color is blue!";
color is green!";
?>
Run example
PHP Arrays
Example
<?php
$cars=array("Volvo","BMW","Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>
Run example
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?
The solution is to create an array!
An array can hold many values under a single name, and you can access the values by referring
to an index number.
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] . ".";
?>
Run example
Example
<?php
$cars=array("Volvo","BMW","Toyota");
echo count($cars);
?>
Run example
Example
<?php
$cars=array("Volvo","BMW","Toyota");
$arrlength=count($cars);
for($x=0;$x<$arrlength;$x++)
{
echo $cars[$x];
echo "<br>";
}
?>
Run example
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.";
?>
Run example
Example
<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
foreach($age as $x=>$x_value)
{
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
?>
Run example
Multidimensional Arrays
Multidimensional arrays will be explained in the PHP advanced section.
Example
<?php
$cars=array("Volvo","BMW","Toyota");
sort($cars);
?>
Run example
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);
?>
Run example
Example
<?php
$cars=array("Volvo","BMW","Toyota");
rsort($cars);
?>
Run example
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);
?>
Run example
Example
<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
asort($age);
?>
Run example
Example
<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
ksort($age);
?>
Run example
Example
<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
arsort($age);
?>
Run example
Example
<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
krsort($age);
?>
Run example