0% found this document useful (0 votes)
901 views25 pages

PHP W3schools Tutorial

This document provides an introduction to PHP. It explains that PHP code is executed on the server, and PHP scripts can contain HTML, JavaScript, and PHP code. It also outlines some basic PHP syntax like using <?php ?> tags. The document then discusses PHP variables like declaring and assigning variables. It also covers PHP data types like strings and functions for manipulating strings.

Uploaded by

Rahul Ambadkar
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
901 views25 pages

PHP W3schools Tutorial

This document provides an introduction to PHP. It explains that PHP code is executed on the server, and PHP scripts can contain HTML, JavaScript, and PHP code. It also outlines some basic PHP syntax like using <?php ?> tags. The document then discusses PHP variables like declaring and assigning variables. It also covers PHP data types like strings and functions for manipulating strings.

Uploaded by

Rahul Ambadkar
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 25

PHP Introduction

PHP code is executed on the server.

What You Should Already Know


Before you continue you should have a basic understanding of the following:

HTML

CSS

If you want to study these subjects first, find the tutorials on our Home page.

What is PHP?

PHP stands for PHP: Hypertext Preprocessor

PHP is a widely-used, open source scripting language

PHP scripts are executed on the server

PHP is free to download and use


PHP is simple for beginners.
PHP also offers many advanced features for professional programmers.

What is a PHP File?

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 files have a default file extension of ".php"

What Can PHP Do?

PHP can generate dynamic page content

PHP can create, open, read, write, and close files on the server

PHP can collect form data

PHP can send and receive cookies

PHP can add, delete, modify data in your database

PHP can restrict users to access some pages on your website

PHP can encrypt data

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 different platforms (Windows, Linux, Unix, Mac OS X, etc.)

PHP is compatible with almost all servers used today (Apache, IIS, etc.)

PHP has support for 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:

Find a web host with PHP and MySQL support

Install a web server on your own PC, and then install PHP and MySQL

Use a Web Host With PHP Support


If your server has activated support for PHP you do not need to do anything.
Just create some .php files, place them in your web directory, and the server will automatically
parse them for you.
You do not need to compile anything or install any extra tools.
Because PHP is free, most web hosts offer PHP support.

Set Up PHP on Your Own PC


However, if your server does not support PHP, you must:

install a web server

install PHP

install a database, such as MySQL

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.

Basic PHP Syntax


A PHP script can be placed anywhere in the document.
A PHP script starts with <?php and ends with ?>:
<?php
// PHP code goes here
?>

The default file extension for PHP files is ".php".


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 sends the text "Hello
World!" 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

Variables are "containers" for storing information:

Example
<?php
$x=5;
$y=6;
$z=$x+$y;
echo $z;
?>
Run example

Much Like Algebra


x=5
y=6
z=x+y
In algebra we use letters (like x) to hold values (like 5).
From the expression z=x+y above, we can calculate the value of z to be 11.
In PHP these letters are called variables.
Think of variables as containers for storing data.

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

A variable name must begin with a letter or the underscore character

A variable name can only contain alpha-numeric characters and underscores


(A-z, 0-9, and _ )

A variable name should not contain spaces

Variable names are case sensitive ($y and $Y are two different variables)
Both PHP statements and PHP variables are case-sensitive.

Creating (Declaring) PHP Variables


PHP has no command for declaring a variable.
A variable is created the moment you first assign a value to it:
$txt="Hello world!";
$x=5;

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.

PHP is a Loosely Typed Language


In the example above, notice that we did not have to tell PHP which data type the variable is.
PHP automatically converts the variable to the correct data type, depending on its value.
In a strongly typed programming language, we will have to declare (define) the type and name of
the variable before using it.

PHP Variable Scopes


The scope of a variable is the part of the script where the variable can be referenced/used.
PHP has four different variable scopes:

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.

PHP String Variables

A string variable is used to store and manipulate text.

String Variables in PHP


String variables are used for values that contain characters.
After we have created a string variable we can manipulate it. A string can be used directly in a
function or it can be stored in a variable.
In the example below, we create a string variable called txt, then we assign the text "Hello
world!" to it. Then we write the value of the txt variable to the output:

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.

The PHP Concatenation Operator


There is only one string operator in PHP.
The concatenation operator (.) is used to join two string values together.
The example below shows how to concatenate two string variables together:

Example
<?php
$txt1="Hello world!";
$txt2="What a nice day!";

echo $txt1 . " " . $txt2;


?>
Run example

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.

The PHP strlen() function


Sometimes it is useful to know the length of a string value.
The strlen() function returns the length of a string, in characters.
The example below returns the length of the string "Hello world!":

Example
<?php
echo strlen("Hello world!");
?>
Run example

The output of the code above will be: 12


Tip: strlen() is often used in loops or other functions, when it is important to know when a string
ends. (i.e. in a loop, we might want to stop the loop after the last character in a string).

The PHP strpos() function


The strpos() function is used to search for a character or a specific text within a string.
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!":

Example
<?php
echo strpos("Hello world!","world");
?>
Run example

The output of the code above will be: 6.


Tip: The position of the string "world" in the example above is 6. The reason that it is 6 (and not
7), is that the first character position in the string is 0, and not 1.

Complete PHP String Reference


For a complete reference of all string functions, go to our complete PHP String Reference.
The PHP string reference contains description and example of use, for each function!
PHP Operators

The assignment operator = is used to assign values to variables in PHP.


The arithmetic operator + is used to add values together in PHP.

PHP Arithmetic Operators


Operator Name

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

Concatenate two strings "Hi" . "Ha"

HiHa

PHP Assignment Operators


The basic assignment operator in PHP is "=". It means that the left operand gets set to the value
of the expression on the right. That is, the value of "$x = 5" is 5.
Assignme
Same as...
nt

Description

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

a .= b

a=a.b

Concatenate two strings

PHP Incrementing/Decrementing Operators


Operator Name

Description

++ x

Pre-increment

Increments x by one, then returns x

x ++

Post-increment

Returns x, then increments x by one

-- x

Pre-decrement

Decrements x by one, then returns x

x --

Post-decrement Returns x, then decrements x by one

PHP Comparison Operators


Comparison operators allows you to compare two values:
Operator Name

Description

Example

x == y

Equal

True if x is equal to y

5==8 returns false

x === y

Identical

True if x is equal to y, and


they are of same type

5==="5" returns false

x != y

Not equal

True if x is not equal to y

5!=8 returns true

x <> y

Not equal

True if x is not equal to y

5<>8 returns true

x !== y

Not identical

True if x is not equal to y, or


they are not of same type

5!=="5" returns true

x>y

Greater than

True if x is greater than y

5>8 returns false

x<y

Less than

True if x is less than y

5<8 returns true

x >= y

Greater than or True if x is greater than or


equal to
equal to y

5>=8 returns false

x <= y

Less than or
equal to

5<=8 returns true

True if x is less than or equal


to y

PHP Logical Operators


Operator Name

x and y

x or y

x xor y

x && y

Description

Example

True if both x and y are true

x=6
y=3
(x < 10 and y > 1)
returns true

Or

True if either or both x and y


are true

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

True if both x and y are true

x=6
y=3
(x < 10 && y > 1)
returns true

And

x || y

Or

True if either or both x and y


are true

x=6
y=3
(x==5 || y==5) returns
false

!x

Not

True if x is not true

x=6 y=3
!(x==y) returns true

PHP Array Operators


Operator Name

Description

x+y

Union

Union of x and y

x == y

Equality

True if x and y have the same key/value pairs

x === y

Identity

True if x and y have the same key/value pairs in the

same order and are of the same type


x != y

Inequality

True if x is not equal to y

x <> y

Inequality

True if x is not equal to y

x !== y

Non-identity

True if x is not identical to y

PHP If...Else Statements

Conditional statements are used to perform different actions based on different conditions.

PHP Conditional Statements


Very often when you write code, you want to perform different actions for different decisions.
You can use conditional statements in your code to do this.
In PHP we have the following conditional statements:

if statement - executes some code only if a specified condition is true

if...else statement - executes some code if a condition is true and another


code if the condition is false

if...else if....else statement - selects one of several blocks of code to be


executed

switch statement - selects one of many blocks of code to be executed

PHP - The if Statement


The if statement is used to execute some code only if a specified condition is true.
Syntax
if (condition)
{
code to be executed if condition is true;
}

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

PHP - The if...else Statement


Use the if....else statement to execute some code if a condition is true and another code if the
condition is false.
Syntax
if (condition)
{
code to be executed if condition is true;
}
else
{
code to be executed if condition is false;
}

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

PHP - The if...else if....else Statement


Use the if....else if...else statement to select one of several blocks of code to be executed.
Syntax
if (condition)
{
code to be executed if condition is true;
}
else if (condition)
{
code to be executed if condition is true;
}
else
{
code to be executed if condition is false;
}

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

PHP - The switch Statement


The switch statement will be explained in the next chapter.

PHP Switch Statement

The switch statement is used to perform different actions based on different conditions.

The PHP Switch Statement


Use the switch statement to select one of many blocks of code to be executed.
Syntax
switch (n)
{
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
break;
default:
code to be executed if n is different from both label1 and label2;
}

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!";

color is neither red, blue, or green!";

?>
Run example

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] . ".";
?>
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.

Create an Array in PHP


In PHP, the array() function is used to create an array:
array();

In PHP, there are three types of arrays:

Indexed arrays - Arrays with numeric index

Associative arrays - Arrays with named keys

Multidimensional arrays - Arrays containing one or more arrays

PHP Indexed Arrays


There are two ways to create indexed arrays:
The index can be assigned automatically (index always starts at 0):
$cars=array("Volvo","BMW","Toyota");

or the index can be assigned manually:


$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] . ".";
?>
Run example

Get The Length of an Array - The count() Function


The count() function is used to return the length (the number of elements) of an array:

Example
<?php
$cars=array("Volvo","BMW","Toyota");
echo count($cars);
?>
Run example

Loop Through an Indexed Array


To loop through and print all the values of an indexed array, you could use a for loop, like this:

Example
<?php
$cars=array("Volvo","BMW","Toyota");
$arrlength=count($cars);
for($x=0;$x<$arrlength;$x++)
{
echo $cars[$x];
echo "<br>";
}
?>
Run example

PHP Associative Arrays


Associative arrays are arrays that use named keys that you assign to them.
There are two ways to create an associative array:
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");

or:
$age['Peter']="35";
$age['Ben']="37";
$age['Joe']="43";

The named keys can then be used in a script:

Example
<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
echo "Peter is " . $age['Peter'] . " years old.";
?>
Run example

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");
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.

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 Sorting Arrays

The elements in an array can be sorted in alphabetical or numerical order, descending or


ascending.

PHP - Sort Functions For Arrays


In this chapter, we will go through the following PHP array sort functions:

sort() - sort arrays in ascending order

rsort() - sort arrays in descending order

asort() - sort associative arrays in ascending order, according to the value

ksort() - sort associative arrays in ascending order, according to the key

arsort() - sort associative arrays in descending order, according to the value

krsort() - sort associative arrays in descending order, according to the key

Sort Array in Ascending Order - sort()


The following example sorts the elements of the $cars array in ascending alphabetical order:

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

Sort Array in Descending Order - rsort()


The following example sorts the elements of the $cars array in descending alphabetical order:

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

Sort Array in Ascending Order, According to Value - asort()


The following example sorts an associative array in ascending order, according to the value:

Example
<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
asort($age);
?>
Run example

Sort Array in 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);
?>
Run example

Sort Array in Descending Order, According to Value - arsort()


The following example sorts an associative array in descending order, according to the value:

Example
<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
arsort($age);
?>
Run example

Sort Array in Descending Order, According to Key - krsort()


The following example sorts an associative array in descending order, according to the key:

Example
<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
krsort($age);
?>
Run example

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!

You might also like