PHP – an acronym for “PHP: Hypertext Preprocessor“, is a widely-used, free, open-source server scripting language that allows web developers to develop dynamic and interactive web pages.
Some important points that you need to know before proceeding further are listed below:
- PHP Files have extension .php.
- PHP files can contain text, HTML, CSS, JavaScript, and PHP code that is executed on server and output is returned to the browser as HTML.
- PHP is platform and server friendly as it’s compatible with almost all platforms and servers. It also supports many databases.
Installation
There are 3 ways through which you can start working with PHP, which are listed and explained below:
Using a web-host with PHP Support
As PHP is free and most web-host offer PHP support. So, if PHP support is offered by your server, then no compilation or installation is needed, all you need to do is:
- Create .php file
- Place them in web Directory and server will compile them automatically
Setting Up PHP on your PC
If the above solution is not feasible then you can follow the following steps to install PHP on your PC:
- First, you need to install a web server
- Then, install PHP from their official website Php.net and follow Installation Guidelines.
- Install any Database of your choice.
Using Online Editor/compiler
There are many online PHP editors are available. So, you can use those online compilers too without any need for installation. But in long term, it’s more feasible to use the above 2 methods.
Syntax
PHP Script starts with <?php
and ends with ?>
. Basic PHP script is shown below:
<?php // PHP code goes here ?>
Some points you need to remember are:
- PHP Script can be placed anywhere in the document
- PHP Statements end with semicolon ( ; )
- Except for variable names, nothing is case sensitive in PHP
Example:
<!DOCTYPE html> <html> <body> <h1>PHP page</h1> <?php echo "Hello World!"; ?> </body> </html>
Variables
Like in other programming languages, In PHP variables are used as containers for storing information.
Variable Syntax
Following Syntax rules should be kept in mind while dealing with variables in PHP:
- In PHP, variable stars with $ sign, followed by the name of the variable.
- Datatype of variable is not required in PHP
- String values are enclosed in double quotes
- Variable name must start with a letter or underscore.
- Variable names only comprise of alphabets or alphanumeric characters
- Variable names are case-sensitive
- Echo statement is used to output variables or text
Example:
<?php $text = "Hello world!"; $number = 5; $float_number = 10.5; echo $text // will print Hello world echo $number; // will print 5 echo $float_number; // will print 10.5 ?>
PHP Comments
Like other programming languages, In PHP comments are lines that are not executed.
Comments Syntax
Comments can be declared in two ways:
<?php // A single-line comment # Another way to declare a single-line comment /* Multiple-line comments Can be declared in this way. */ ?>
Output
There are two ways to display output in PHP :
- Using echo statement
- Using print statement
Both are described below:
Echo Statement
Below are some points you need to remember about echo statement :
- Echo statement is used to display text and output variables.
- It can be used with or without parentheses i.e., echo() or echo .
- It has no return value.
- It can take more than 1 parameters.
- Html Markups can be used in ouput text.
- Echo is little bit faster than print Statement.
Examples
<?php //Displaying text echo "<h2>Let’s Learn PHP</h2>"; echo "Displaying ", "Text ", "using ", "multiple ", "parameters."; //Displaying Variables $text1 = "Learning PHP"; $text2 = "Hello world!"; $num1 = 7; $num2 = 2; echo "<h2>" . $text1 . "</h2>"; echo $text2 echo $num1 + $num1; ?>
Print Statement
Below are some points you need to remember about Print statement :
- Print statement is used to display text and output variables.
- It can be used with or without parentheses i.e., print() or print.
- It has a return value of 1 so it can be used in expressions.
- It takes only 1 argument.
- Html Markups can be used in output text.
Examples
<?php //Displaying text print "<h2>Let’s Learn PHP</h2>"; print "Hello world...<br>"; //Displaying Variables $text1 = "Learning PHP"; $text2 = "Hello world!"; $num1 = 7; $num2 = 2; print "<h2>" . $text1 . "</h2>"; print $text2 print $num1 + $num1; ?>
Operators
Operators are used to perform operations on values or variables, generally converting them to complex expressions.
We will discuss types of operators one by one:
Assignment operators
Assignment operators are used to assign values to PHP variables.
The following table contains commonly used Assignment operators:
Operator | Usage | Example |
= | Assigns value to variable |
<?php $x = 20; echo $x; //Output: 20 ?> |
+= | Adds a value to a variable. |
<?php $x = 20; $x += 20; echo $x; //Output: 40 ?> |
-= | Subtracts a value from a variable. |
<?php $x = 20; $x -= 10; echo $x; //Output: 10 ?> |
*= | Multiplies a variable. |
<?php $x = 2; $x *= 10; echo $x; //Output: 20 ?> |
/= | Divides a variable |
<?php $x = 20; $x /= 10; echo $x; //Output: 2 ?> |
%= | Assigns a remainder to a variable |
<?php $x = 20; $x %= 3; echo $x; //Output: 2 ?> |
Arithmetic Operators
Arithmetic operators are used to perform arithmetic on numeric values. You must be familiar with following two terms:
- Operators: Defines the operation to be performed e.g. multiplication, addition etc.
- Operands: Numbers in an arithmetic operation is performed
The following table contains commonly used Arithmetic operators:
Operator | Usage | Example |
“+” (Addition) |
Adds numbers |
<?php $x = 2; $y = 5; echo $x + $y; //Output: 7 ?> |
“-” (Subtraction) |
Subtracts Numbers |
<?php $x = 20; $y = 5; echo $x - $y; //Output: 15 ?> |
“*” (Multiplication) |
Multiplies Numbers |
<?php $x = 2; $y = 5; echo $x * $y; //Output: 10 ?> |
“/”
(Division) |
Divides Numbers |
<?php $x = 20; $y = 5; echo $x / $y; //Output: 4 ?> |
“%” (Modulus) |
Returns Reminder of division |
<?php $x = 20; $y = 3; echo $x % $y; //Output: 2 ?> |
“**” (Exponentiation) |
Raises the first operand to the power of 2nd operand |
<?php $x = 5; $y = 2; echo $x ** $y; //Output: 25 ?> |
Increment/decrement Operators
- Increment Operator is used to increment variable’s value.
- Decrement Operator is used to decrement variable’s value.
Operator | Usage | Example |
“++$x” (Pre-Increment) |
First Increments “x”, then return “x” |
<?php $x = 20; echo ++$x; //Output: 21 ?> |
“$x++” (Post-Increment) |
First returns “x”, then Increments”x” |
<?php $x = 20; echo $x++; //Output: 20 ?> |
“–$x” (Pre-Decrement) |
First Decrements “x”, then return “x” |
<?php $x = 20; echo --$x; //Output: 19 ?> |
“$x–” (Post-Decrement) |
First returns “x”, then Decrements”x” |
<?php $x = 20; echo $x--; //Output: 20 ?> |
Comparison operators
Comparison operators are used in logical statements for comparison(Equality or difference) between values or variables and upon evaluation return True or False.
The following table contains commonly used Comparison operators:
Operator | Usage | Example |
== | Equal to (Returns True if both values are equal) |
<?php $x = 20; $y = "20"; var_dump($x == $y); //Output: bool(true) as values are equal ?> |
=== | Equal value And Same type (Returns True if both values are equal and of same type) |
<?php $x = 20; $y = "20"; var_dump($x === $y); //Output: bool(false) as values are not of same type ?> |
!= or <> |
Not Equal to (Returns True if both values are not equal) |
<?php $x = 20; $y = "20"; var_dump($x <> $y); var_dump($x != $y); //Both will Output: bool(false) as values are equal ?> |
!== | Not Equal value or not Equal type (Returns True if both values are not equal or not of same type) |
<?php $x = 20; $y = "20"; var_dump($x != $y); //Output: bool(True) as types are not same ?> |
> | Greater than |
<?php $x = 20; $y = 2; var_dump($x > $y); //Output: bool(True) as x is greater than y ?> |
< | Less than |
<?php $x = 2; $y = 20; var_dump($x < $y); //Output: bool(True) as x is less than y ?> |
>= | Greater than or equal to |
<?php $x = 20; $y = 20; var_dump($x >= $y); //Output: bool(True) as x is greater than or equal to y ?> |
<= | Less than or equal to |
<?php $x = 20; $y = 20; var_dump($x <= $y); //Output: bool(True) as x is less than or equal to y ?> |
<=> | Spaceship
(Returns “-1” if variable on left is less than variable on right, “0” if both values are equal, “+1” if variable on left is greater than variable on right ) |
<?php $x = 20; $y = 20; var_dump($x <=> $y); //Output:Returns "0" as x is equal to y ?> |
Logical Operators
Logical operators are used in logical statements to determine logic between values or variables and upon evaluation return True or False.
The following table contains commonly used Comparison operators:
Operator | Usage | Example |
&& or and |
AND (Returns True if both expressions are True else return False) |
<?php $x = 20; $y = 50; if ($x == 20 && $y == 50) { echo "True"; } else echo "False"; //Output: True as both statements are true ?> |
|| or or |
OR (Returns False if both expressions are false else return True) |
<?php $x = 20; $y = 50; if ($x == 10 or $y == 40) { echo "True"; } else echo "False"; //Output: False as both statements are false ?> |
! | NOT (Returns True if expression is false else return true) |
<?php $x = 20; if ($x != 10) { echo "True"; } else echo "False"; //Output: True as statement is true ?> |
xor | XOR (Returns True if either x or y is true and not both are true or false ) |
<?php $x = 20; $y = 10; if ($x == 10 xor $y == 30) { echo "True"; } else echo "False"; //Output: True as statement 1 is true ?> |
String Operators
In PHP “.” and “.=” operators are used to add (concatenate) the strings.
Example | Output |
$string1 = "Alia "; $string2 = "Ahmed"; echo $string1 . $string2; |
Alia Ahmed |
$string1 = "Alia "; $string2 = "Ahmed"; $string1 .= $string2; echo $string1; |
Alia Ahmed |
Conditions
Conditional operators are used when you want to perform different actions based on different decisions.
The following table shows conditional operators:
Operator | Usage | Examples |
if | Used to specify a block of code that should be executed if the condition is true else the if block will not be executed. (Can be used alone) |
$x = 20; if ($x > 0) { // do something } |
else | Used to specify a block of code that should be executed if the condition in “if block” is false. (As you know else cannot be used alone it must be followed by an if statement ) |
$x = 20; if ($x > 0) { // do something } else { // do something else } |
else if | Used to specify a block of code with a new condition that should be executed if the condition in “if block” is false. (As you know else if cannot be used alone it must be followed by an if statement or an else if statement) |
$x = 20; if ($x = 0) { // do something if condition is true } else if ($x > 0) { // do something if condition in if is false and this condition is true } else { // do something if both of the above conditions i.e. in if and else if are false } |
switch | Used to select one code block to be executed out of many. (After the evaluation of expression in switch statement the resultant value is compared to every case and if there is a match that code block is executed. If none of the cases is matched then the default code block is executed. Remember only one case is executed as after each case it breaks out of switch block ) |
switch(expression) { case x: // code block break; case y: // code block break; default: // code block } |
Loops
Loops are used to execute a block of the code a number of times.
In PHP we have 4 kinds of Loops described in table below:
Loop Keyword | Usage & Syntax | Examples |
for | for (initialization; condition; increment/decrement) { // code block to be executed } |
<?php for ($x = 0; $x <= 50; $x+=2) { echo "Value of x is: $x <br>"; } i++; } |
foreach | foreach ($array as $value) { // code block to be executed }(Note: It is used to loop through the key/value pair of array.) |
(1)Looping array containing only values
<?php $colors = array("red", "green", "blue", "yellow"); foreach ($colors as $value) { echo "$value <br>"; } ?> } (2)Looping array containing both keys and values <?php $employeeAge = array("Alia"=>"35", "john"=>"37"); foreach($employeeAge as $y => $val) { echo "$y = $val<br>"; } ?> |
while | while (condition) { // code block to be executed }(Note: The code block is executed as long as condition is true ) |
<?php $x = 10; while($x <= 50) { echo "The number is: $x <br>"; $x++; } ?> |
do while | do { // code block to be executed } while (condition);(Note: Code block will be executed before checking if the condition is true, then the loop will be repeated as long as the condition is true. Even if the condition is false , loop will be executed at least once. ) |
<?php $x = 10; do { echo "The number is: $x <br>"; $x++; } while ($x <= 50); ?> |
Arrays
In PHP, Array is used to store multiple values in a single variable and array() function is used to create array in PHP.
Moreover, there are 3 types of arrays in PHP:
- Indexed arrays
- Associative arrays
- Multidimensional arrays
We will discuss them one by one.
Indexed Arrays
Arrays with numeric indexes are called Indexed arrays.
Creating Indexed Arrays
Method-1
<?php $colors = array("red", "green", "blue", "yellow"); echo "My favorite colors are " . $colors[0] . ", " . $colors[1] . ", " . $colors[2] . " and " . $colors[3] . "."; ?>
Method-2
<?php $colors[0] = "red"; $colors[1] = "green"; $colors[2] = "yellow"; $colors[2] = "blue"; echo "My favorite colors are " . $colors[0] . ", " . $colors[1] . ", " . $colors[2] . " and " . $colors[3] . "."; ?>
Iterating Indexed Array
Using for Loop
<?php $colors = array("red", "green", "blue", "yellow"); $arraylength = count($colors); for($x = 0; $x < $arraylength; $x++) { echo $colors[$x]; echo "<br>"; } ?>
Using foreach Loop
<?php $colors = array("red", "green", "blue", "yellow"); foreach ($colors as $value) { echo "$value <br>"; } ?>
Associative Arrays
Arrays that use user-defined name keys are called Associative Arrays.
Creating Associative Arrays
Method-1
<?php $employeeAge = array("Alia"=>"35", "john"=>"37"); echo "Alia is " . $employeeAge['Alia'] . " years old and John is " . $employeeAge['John'] . " years old."; ?>
Method-2
<?php $employeeAge['Alia'] = "35"; $employeeAge['John'] = "37"; echo "Alia is " . $employeeAge['Alia'] . " years old and John is " . $employeeAge['John'] . " years old."; ?>
Iterating Associative Array
<?php $employeeAge = array("Alia"=>"35", "john"=>"37"); foreach($employeeAge as $y => $val) { echo "$y = $val<br>"; } ?>
Multi Dimensional Array
Arrays containing one or more arrays are called multi-dimensional Arrays.
Creating Multi Dimensional Array
<?php $employees = array ( array("John",22,18,000), array("Alia",35,25,000) ); echo $employees[0][0].": Age: ".$employees[0][1].", salary: ".$employees[0][2].".<br>"; echo $employees[1][0].": Age: ".$employees[1][1].", salary: ".$employees[1][2]."."; ?>
Iterating Multi Dimensional Array
<?php $employees = array ( array("John",22,18,000), array("Alia",35,25,000) ); for ($row = 0; $row < 2; $row++) { echo "<p><b>Row $row</b></p>"; echo "<ul>"; for ($col = 0; $col < 3; $col++) { echo "<li>".$employees[$row][$col]."</li>"; } echo "</ul>"; } ?>
Strings
PHP strings are sequences of zero or more characters that are used as containers to store and manipulate text.
Strings are written inside single ” (Single Quote strings don’t replace variables with their values) or double quotes “” (Double Quote strings replace variables with their values).
Example:
$fruit= "Apple"; $string= ""; // Empty string
String Functions
Some important String Functions in PHP are mentioned in following table:
String Function | Usage | Example |
strlen() | Returns length of string |
<?php echo strlen("Alia"); // outputs 4 ?> |
str_word_count() | Returns No of words in Given String |
<?php echo str_word_count("My name is Alia"); // outputs 4 ?> |
strrev() | Reverse Given String |
<?php echo strrev("Alia"); // outputs ailA ?> |
strpos() | Returns index of text found in string.If text is not found it returns false. |
<?php echo strpos("My name is Alia", "name"); // outputs 3 ?> |
str_replace() | Replace some characters of string with other given characters. |
<?php echo str_replace("Alia", "John", "My name is Alia"); // outputs My name is John ?> |
Functions
Functions are a block of code designed to perform a particular task. Like functions in other programming languages, the syntax of PHP functions is almost similar.
In PHP, there are many built-in functions and users can define their own functions too.
Note:
- Function name starts with a letter or underscore.
- Function Names are not case-sensitive
Syntax:
function functionName (parameter1, parameter2,..) { // code to be executed }
Examples:
Example -1
<?php function displayText($text) { echo "$text <br>"; } displayText("Hello World"); ?>
Example -2
<?php declare(strict_types=1); // strict requirement to specify expected data type when declaring a function. It will show error if data type mismatches as declared in function function sumValues(int $x, int $y) { return $x + $y; // return statement to return values } echo "Sum of 5 and 10 is " . sum(5, 10) . "<br>"; ?>