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 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>
PHP Case Sensitivity
In PHP, keywords (e.g. if, else, while, echo, etc.), classes, functions, and user-defined functions are not case-sensitive.
In the example below, all three echo statements below are equal and legal:
Example
<!DOCTYPE html> <html> <body> <h1>My first PHP page</h1> <?php echo "Hello World!"; ?> </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.
PHP supports several ways of commenting:
Example
Syntax for single-line comments:
<!DOCTYPE html> <html> <body> <?php // This is a single-line comment # This is also 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>
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; ?>
Output Variables
The PHP echo statement is often used to output data to the screen.
The following example will show how to output text and a variable:
Example
<?php $txt = "W3Schools.com"; echo "I love $txt!"; ?>
PHP echo and print Statements
echo and print are more or less the same. They are both used to output data to the screen.
The differences are small: echo has no return value while print has a return value of 1 so it can be used in expressions. echo can take multiple parameters (although such usage is rare) while print can take one argument. echo is marginally faster than print.
The PHP echo Statement
The echo statement can be used with or without parentheses: echo or echo().
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."; ?>
The PHP print Statement
The print statement can be used with or without parentheses: print or print().
Example
<?php print "<h2>PHP is Fun!</h2>"; print "Hello world!<br>"; print "I'm about to learn PHP!"; ?>
PHP Data Types
Variables can store data of different types, and different data types can do different things.
PHP supports the following data types:
- String
- Integer
- Float
- 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.
In the following example $x is an integer. The PHP var_dump() function returns the data type and value:
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.
Example
$x = true; $y = false;
PHP Array
An array stores multiple values in one single variable.
In the following example $cars is an array. The PHP var_dump() function returns the data type and value:
Example
<?php $cars = array("Volvo" ,"BMW", "Toyota"); var_dump($cars); ?>
PHP Object
Classes and objects are the two main aspects of object-oriented programming.
A class is a template for objects, and an object is an instance of a class.
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 . "!"; } } $myCar = new Car("black", "Volvo"); echo $myCar -> message(); echo "<br>"; $myCar = new Car("red", "Toyota"); echo $myCar -> message(); ?>
PHP NULL Value
Null is a special data type which can have only one value: NULL.
A variable of data type NULL is a variable that has no value assigned to it.
Variables can also be emptied by setting the value to NULL:
Example
<?php $x = "Hello world!"; $x = null; var_dump($x); ?>
PHP String Functions
In this chapter we will look at some commonly used functions to manipulate strings.
strlen() - Return the Length of a String
The PHP strlen() function returns the length of a string.
Example
Return the length of the string "Hello world!":
<?php echo strlen("Hello world!"); // outputs 12 ?>
str_word_count() - Count Words in a String
The PHP str_word_count() function counts the number of words in a string.
Example
The PHP str_word_count() function counts the number of words in a string.
<?php echo str_word_count("Hello world!"); // outputs 2 ?>
strrev() - Reverse a String
The PHP strrev() function reverses a string.
Example
Reverse the string "Hello world!":
<?php echo strrev("Hello world!"); // outputs !dlrow olleH ?>
strpos() - Search For a Text Within a String
The PHP strpos() function searches for a specific text within a string. If a match is found, the function returns the character position of the first match. If no match is found, it will return FALSE.
Example
Search for the text "world" in the string "Hello world!":
<?php echo strpos("Hello world!", "world"); // outputs 6 ?>
str_replace() - Replace Text Within a String
The PHP str_replace() function replaces some characters with some other characters in a string.
Example
Replace the text "world" with "Dolly":
<?php echo str_replace("world", "Dolly", "Hello world!"); // outputs Hello Dolly! ?>
PHP Numbers
One thing to notice about PHP is that it provides automatic data type conversion.
So, if you assign an integer value to a variable, the type of that variable will automatically be an integer. Then, if you assign a string to the same variable, the type will change to a string.
This automatic conversion can sometimes break your code.
PHP Integers
An integer is a number without any decimal part
An integer data type is a non-decimal number between -2147483648
and
2147483647
in 32 bit systems,
and between -9223372036854775808
and 9223372036854775807
in
64
bit systems. A value greater (or
lower) than this, will be stored as float, because it exceeds the limit of an integer.
Example
Check if the type of a variable is integer:
<?php $x = 5985; var_dump(is_int($x)); $x = 59.85; var_dump(is_int($x)); ?>
PHP Floats
A float is a number with a decimal point or a number in exponential form.
e float data type can commonly store a value up to 1.7976931348623E+308
(platform
dependent), and
have a maximum precision of 14 digits.
Example
Check if the type of a variable is float:
<?php $x = 10.365; var_dump(is_float($x)); ?>
PHP Infinity
A numeric value that is larger than PHP_FLOAT_MAX is considered infinite.
Example
Check if a numeric value is finite or infinite:
<?php $x = 1.9e411; var_dump($x); ?>
PHP NaN
NaN stands for Not a Number.
NaN is used for impossible mathematical operations.
Example
Invalid calculation will return a NaN value:
<?php $x = acos(8); var_dump($x); ?>
PHP pi() Function
The pi() function returns the value of PI:
Example
<?php echo(pi()); // returns 3.1415926535898 ?>
PHP min() and max() Functions
The min() and max() functions can be used to find the lowest or highest value in a list of arguments:
Example
<?php echo(min(0, 150, 30, 20, -8, -200)); // returns -200 echo(max(0, 150, 30, 20, -8, -200)); // returns 150 ?>
PHP abs() Function
The abs() function returns the absolute (positive) value of a number:
Example
<?php echo(abs(-6.7)); // returns 6.7 ?>
PHP sqrt() Function
The sqrt() function returns the square root of a number:
Example
<?php echo(sqrt(64)); // returns 8 ?>
PHP round() Function
The round() function rounds a floating-point number to its nearest integer:
Example
<?php echo(round(0.60)); // returns 1 echo(round(0.49)); // returns 0 ?>
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).
Create a PHP Constant
To create a constant, use the define() function.
Syntax
<?php define("GREETING", "Welcome to W3Schools.com!"); echo GREETING; ?>
PHP Constant Arrays
In PHP7, you can create an Array constant using the define() function.
Example
Create an Array constant:
<?php define("cars", [ "Alfa Romeo", "BMW", "Toyota" ]); echo cars[0]; ?>
Constants are Global
Constants are automatically global and can be used across the entire script.
Example
<?php define("GREETING", "Welcome to W3Schools.com!"); function myTest() { echo GREETING; } myTest(); ?>
PHP Conditional Statements
Very often when you write code, you want to perform different actions for different conditions. You can use conditional statements in your code to do this.
PHP - The if Statement
The if statement executes some code if one condition is true.
Example
Output "Have a good day!" if the current time (HOUR) is less than 20:
<?php $t = date("H"); if ($t < "20") { echo "Have a good day!"; } ?>
PHP - The if...else Statement
The if...else statement executes some code if a condition is true and another code if that condition is false.
Example
<php $t = date("H"); if ($t < "20") { echo "Have a good day!"; } else { echo "Have a good night!"; } ?>
PHP - The if...elseif...else Statement
The if...elseif...else statement executes different codes for more than two conditions.
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"); if ($t < "10") { echo "Have a good morning!"; } elseif ($t < "20") { echo "Have a good day!"; } else { echo "Have a good night!"; } ?>
The PHP switch Statement
Use the switch statement to select one of many blocks of code to be executed.
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!"; } ?>
PHP Loops
Often when you write code, you want the same block of code to run over and over again a certain number of times. So, instead of adding several almost equal code-lines in a script, we can use loops.
Loops are used to execute the same block of code again and again, as long as a certain condition is true.
The PHP while Loop
The while loop executes a block of code as long as the specified condition is true.
Example
The example below displays the numbers from 1 to 5:
<?php $x = 1; while($x <= 5) { echo "The number is: $x <br>"; $x++; } ?>
The PHP 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.
Example
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:
<?php $x = 1; 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.
Example
The example below displays the numbers from 0 to 10:
<?php for ($x = 0; $x <= 10; $x++) { echo "The number is: $x <br>"; } ?>
The PHP foreach Loop
The foreach loop works only on arrays, and is used to loop through each key/value pair in an array.
Example
The following example will output the values of the given array ($colors):
<?php $colors = array("red", "green", "blue", "yellow"); foreach ($colors as $value) { echo "$value <br>"; } ?>
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.
The break statement can also be used to jump out of a loop.
This example jumps out of the loop when x is equal to 4:
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
This example skips the value of 4:
<?php for ($x = 0; $x < 10; $x++) { if ($x == 4) { continue; } echo "The number is: $x <br>"; } ?>
PHP Built-in Functions
PHP has over 1000 built-in functions that can be called directly, from within a script, to perform a specific task.
Please check out our PHP reference for a complete overview of the PHP built-in functions.
PHP User Defined Functions
Besides the built-in PHP functions, it is possible to create your own functions.
- A function is a block of statements that can be used repeatedly in a program.
- A function will not execute automatically when a page loads.
- A function will be executed by a call to the function.
Create a User Defined Function in PHP
A user-defined function declaration starts with the word function:
Example
In the example below, we create a function named "writeMsg()". The opening curly brace ( { ) indicates the beginning of the function code, and the closing curly brace ( } ) indicates the end of the function. The function outputs "Hello world!". To call the function, just write its name followed by brackets ():
<?php function writeMsg() { echo "Hello world!"; } writeMsg(); // call the function ?>
What is an Array?
An array is a special variable, which can hold more than one value at a time.
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.
In PHP, there are three types of arrays:
- Indexed arrays - Arrays with a numeric index
- Associative arrays - Arrays with named keys
- Multidimensional arrays - Arrays containing one or more arrays
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); ?>
PHP Global Variables - Superglobals
Some predefined variables in PHP are "superglobals", which means that they are always accessible, regardless of scope - and you can access them from any function, class or file without having to do anything special.
The PHP superglobal variables are:
- $GLOBALS
- $_SERVER
- $_REQUEST
- $_POST
- $_GET
- $_FILES
- $_ENV
- $_COOKIE
- $_SESSION
What is a Regular Expression?
A regular expression is a sequence of characters that forms a search pattern. When you search for data in a text, you can use this search pattern to describe what you are searching for.
A regular expression can be a single character, or a more complicated pattern
Regular expressions can be used to perform all types of text search and text replace operations.
Using preg_match()
The preg_match() function will tell you whether a string contains matches of a pattern.
Example
Use a regular expression to do a case-insensitive search for "w3schools" in a string:
<?php $str = "Visit W3Schools"; $pattern = "/w3schools/i"; echo preg_match($pattern, $str); // Outputs 1 ?>
Using preg_match_all()
The preg_match_all() function will tell you how many matches were found for a pattern in a string.
Use a regular expression to do a case-insensitive count of the number of occurrences of "ain" in a string:
Example
<?php $str = "The rain in SPAIN falls mainly on the plains."; $pattern = "/ain/i"; echo preg_match_all($pattern, $str); // Outputs 4 ?>
PHP - A Simple HTML Form
The example below displays a simple HTML form with two input fields and a submit button:
Example
<html> <body> <form action="welcome.php" method="post"> Name: <input type="text" name="name"><br> E-mail: <input type="text" name="email"><br> <input type="submit"> </form> </body> </html>
Example
The same result could also be achieved using the HTTP GET method:
<html> <body> <form action="welcome_get.php" method="get"> Name: <input type="text" name="name"><br> E-mail: <input type="text" name="email"><br> <input type="submit"> </form> </body> </html>
PHP Form Validation
The HTML form we will be working at in these chapters, contains various input fields: required and optional text fields, radio buttons, and a submit button:
Text Fields
The name, email, and website fields are text input elements, and the comment field is a textarea. The HTML code looks like this:
syntax
type="text" name="name"> type="text" name="email"> type="text" name="website"> area name="comment" rows="5" cols="40"></textarea>
Radio Buttons
The gender fields are radio buttons and the HTML code looks like this:
syntax
radio" name="gender" value="female">Female radio" name="gender" value="male">Male radio" name="gender" value="other">Other
The Form Element
The HTML code of the form looks like this:
syntax
="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
PHP - Required Fields
syntax
<?php // define variables and set to empty values $nameErr = $emailErr = $genderErr = $websiteErr = ""; $name = $email = $gender = $comment = $website = ""; if ($_SERVER["REQUEST_METHOD"] == "POST") { if (empty($_POST["name"])) { $nameErr = "Name is required"; } else { $name = test_input($_POST["name"]); } if (empty($_POST["email"])) { $emailErr = "Email is required"; } else { $email = test_input($_POST["email"]); } if (empty($_POST["website"])) { $website = ""; } else { $website = test_input($_POST["website"]); } if (empty($_POST["comment"])) { $comment = ""; } else { $comment = test_input($_POST["comment"]); } if (empty($_POST["gender"])) { $genderErr = "Gender is required"; } else { $gender = test_input($_POST["gender"]); } } ?>
PHP - Display The Error Messages
Then in the HTML form, we add a little script after each required field, which generates the correct error message if needed (that is if the user tries to submit the form without filling out the required fields):
Example
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"> Name: <input type="text" name="name"> <span class="error">* <?php echo $nameErr;?></span> <br><br> E-mail: <input type="text" name="email"> <span class="error">* <?php echo $emailErr;?></span> <br><br> Website: <input type="text" name="website"> <span class="error"><?php echo $websiteErr;?></span> <br><br> Comment: <textarea name="comment" rows="5" cols="40"></textarea> <br><br> Gender: <input type="radio" name="gender" value="female">Female <input type="radio" name="gender" value="male">Male <input type="radio" name="gender" value="other">Other <span class="error">* <?php echo $genderErr;?></span> <br><br> <input type="submit" name="submit" value="Submit"> </form>
PHP - Validate Name
The code below shows a simple way to check if the name field only contains letters, dashes, apostrophes and whitespaces. If the value of the name field is not valid, then store an error message:
syntax
$name = test_input($_POST["name"]); if (!preg_match("/^[a-zA-Z-' ]*$/",$name)) { $nameErr = "Only letters and white space allowed"; }
PHP - Validate E-mail
The easiest and safest way to check whether an email address is well-formed is to use PHP's filter_var() function.
In the code below, if the e-mail address is not well-formed, then store an error message:
syntax
put($_POST["email"]); $email, FILTER_VALIDATE_EMAIL)) { alid email format";
PHP - Validate URL
The code below shows a way to check if a URL address syntax is valid (this regular expression also allows dashes in the URL). If the URL address syntax is not valid, then store an error message
syntax
input($_POST["website"]); "/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;] * [-a-z0-9+&@#\/%=~_|]/i",$website)) { nvalid URL";
PHP - Validate Name, E-mail, and URL
Now, the script looks like this:
Example
<?php // define variables and set to empty values $nameErr = $emailErr = $genderErr = $websiteErr = ""; $name = $email = $gender = $comment = $website = ""; if ($_SERVER["REQUEST_METHOD"] == "POST") { if (empty($_POST["name"])) { $nameErr = "Name is required"; } else { $name = test_input($_POST["name"]); // check if name only contains letters and whitespace if (!preg_match("/^[a-zA-Z-' ]*$/",$name)) { $nameErr = "Only letters and white space allowed"; } } if (empty($_POST["email"])) { $emailErr = "Email is required"; } else { $email = test_input($_POST["email"]); // check if e-mail address is well-formed if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { $emailErr = "Invalid email format"; } } if (empty($_POST["website"])) { $website = ""; } else { $website = test_input($_POST["website"]); // check if URL address syntax is valid (this regular expression also allows dashes in the URL) if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) { $websiteErr = "Invalid URL"; } } if (empty($_POST["comment"])) { $comment = ""; } else { $comment = test_input($_POST["comment"]); } if (empty($_POST["gender"])) { $genderErr = "Gender is required"; } else { $gender = test_input($_POST["gender"]); } } ?>
PHP - Keep The Values in The Form
To show the values in the input fields after the user hits the submit button, we add a little PHP script inside the value attribute of the following input fields: name, email, and website. In the comment textarea field, we put the script between the <textarea> and </textarea> tags. The little script outputs the value of the $name, $email, $website, and $comment variables.
Then, we also need to show which radio button that was checked. For this, we must manipulate the checked attribute (not the value attribute for radio buttons):
Example
Name: <input type="text" name="name" value="<?php echo $name;?>"> E-mail: <input type="text" name="email" value="<?php echo $email;?>"> Website: <input type="text" name="website" value="<?php echo $website;?>"> Comment: <textarea name="comment" rows="5" cols="40"><?php echo $comment;?></textarea> Gender: <input type="radio" name="gender" <?php if (isset($gender) && $gender=="female") echo "checked";?> value="female">Female <input type="radio" name="gender" <?php if (isset($gender) && $gender=="male") echo "checked";?> value="male">Male <input type="radio" name="gender" <?php if (isset($gender) && $gender=="other") echo "checked";?> value="other">Other