The PHP script can be created in a HTML page, using a special tag: <?php... ?>. So before you learn PHP you should learn HTML. If you do not know yet HTML that’s OK, you will learn some during this tutorial.
<!DOCTYPE html>
<html>
<body>
<?php
echo "Hello World!";
?>
</body>
</html>
Note: When you embed PHP code in an HTML file, you need to use the .php file extension for that file, so that your web server knows to send the file to PHP for processing.
There are about 56 keywords in PHP, compared with 51 in Java. Do not try to memorize this list, it is not a dictionary. But after you finish this tutorial you will know most of them.
abstract | and | array | as |
break | callable | case | catch |
class | clone | const | continue |
declare | default | die | do |
echo | else | elseif | empty |
enddeclare | endfor | endforeach | endif |
endswitch | endwhile | eval | exit |
extends | final | finally | for |
foreach | function | global | goto |
if | implements | include | include_once |
instanceof | insteadof | interface | isset |
list | namespace | new | or |
private | protected | public | |
require | require_once | return | static |
switch | throw | trait | try |
unset | use | var | while |
xor | yield |
PHP comments are like C comments. In addition, symbol "#" will start also a line comment like in Python. Line comments start with "//", block comments are enclosed between "/* ... */".
Note: Remember HTML comments are also possible, using notation <!– .... –>, so you can comment out the entire <php? ... ?> block, but this will not stop the code engine to execute PHP code inside HTML comments. So you can create dynamic comments using PHP. Is that something?
<?php
/* In PHP you can declare variables
of type number using following notation: */
$first = 1; // declare a number
$second = 2.5; // declare second number
/* PHP enable you to concatenate,
but the result may surprise you: */
echo $first.$second; // expected 12.5
?>
Using PHP you can print text into HTML documents. This is done using echo; statement. It can be used with parenthesis (...) that are optional and can have one or multiple arguments, separated by coma. If printable, arguments are output in HTML document as new text.
You can do the same thing with the print statement, except this statement is not going to enable multiple parameters. Statement print is a little bit slower than echo. Print also can be used with (...) and can accept multiple arguments that will be printed one after another.
<?php
// Using "echo"
echo "We say!<br>";
echo "Hello ", "world!", "<br>" ;
// Using "print"
print "You say!<br>";
print "Hello PHP!<br>";
?>
PHP is a dynamic typed programming language. That means a variable in PHP can change its type dynamically. The type of a variable is not usually set by the programmer, rather it is decided at runtime by PHP depending on the context in which that variable is used.
In program we use this concept of data type. At low level data is represented in binary code of 0 and 1. PHP is a high level language so it has support for abstract data types:
Reading next example you will learn quickly literal representation for each type. In PHP you must initialize a variable with a literal or null. You can not define uninitialized variables like you do in C.
<?php
/* string is enclosed in double quotes */
$string1 = "Hello world!"; //double quote string
$string2 = '"Hello world!"'; //single quote string
echo $string1, "<br>";
echo $string2, '<br>';
$i = 123; //positive integer
$n =-123; //negative integer
$d = 1.23; //float
/* boolean and null */
$b = true;
$f = false;
$N = null;
/* do not try to print booleans */
echo "\$b = $b", '<br>'; //unexpected: $b = 1
echo "\$f = $f", '<br>'; //unexpected: $f =
echo "\$N = $N", '<br>'; //unexpected $N =
/* variable introspection var_dump() */
echo var_dump($b), '<br>';
echo var_dump($f), '<br>';
echo var_dump($N), '<br>';
?>
Notes:
Following composite types are available in PHP:
Array Example:
Arrays are 0 based indexed collection of elements. To declare an array we use "array" constructor:
<?php
/* declare array of 3 strings */
$fruits = array("Orange","Banana","Apple");
/* quick introspection for debug */
echo var_dump($fruits), "<br><br>";
/* string interpolation using array elements */
echo "$fruits[0],$fruits[1],$fruits[2]";
?>
Object Example:
An object is a composite data type that have attributes and functions. First we define a "class" that is the object data type. Next we can create one or more "instances" of the class, that are called objects:
<?php
// declare object data type Person
class Person {
function Person($name, $age) {
$this->name = $name;
$this->age = $age;
}
}
// create an object of type Person
$barbu = new Person("Barbu",35);
// show the "name" attribute
echo $barbu->name;
?>
Notes:
In PHP you can create identifiers for constants. These can be used to put assign a name for a value, and avoid repeating same literal in multiple places. Avoiding "magic literals" is a good practice. Constant values can not be modified during program execution.
We use define as keyword with following syntax:
<?php
/* define a constant */
define("HELLO", "Hello World!");
/* use a constant */
echo HELLO;
?>
In PHP we can define names (identifiers) that represent one or more values stored in memory. These identifiers care so called "variable". The value of a variable can be changed during runtime, using an assign statement or a modifier operator. In PHP variable names must have "$" prefix.
<?php
$a = 1; // declare variable $a
$b = 2; // declare variable $b
?>
Expressions are the most important building blocks of PHP. In PHP, almost anything you write is an expression. The simplest yet most accurate way to define an expression is anything that is or produce a value.
The most basic forms of expressions are constant literals and variables. When you type "$a = 5" in CLI, you're assigning '5' into $a. Number 5, obviously, has the value 5, and is called a constant literal. In other words '5' is an expression with the value of 5 (in this case, 5 is an integer constant).
<?php
5 // most simple numeric expression
3 + 2 // arithmetic expression
$a = 5; // declare for variable $a
$a == 5; // logic expression (true)
4/($a + 3); // complex numeric expression
"$a = 8" // string expression
?>
Note:In line 5 you can see a complex expression. That is, small expressions can be combined in larger expressions using operators and delimitors.Terms of a complex expression can be variables, constants and constant literals. An expression, theoretical has a type that is inferred by the operands and operators used in the expression.
An operator is one special character or group of 2 or 3 characters that are considered together as one symbol. Operators are used to connect so called operands and form expressions. The operators represent computations or computing operations that will dictate the result. Depending on data type, we can perform specific operations.
Using operators with wrong data type can lead to errors and unexpected results. Therefore you learn the operators together with the specific data types. Some operators are polymorph. That means operator can act on different data types and can be used to create mixt expressions.
This operator is different than others. The assignment symbol: "=" can be used to setup initial values for a variables to constant literals or expressions. It can be used in combination with other operators to create a "modifier" operators.
<?php
$a = 1; // declare a number
$b = 2; // declare second number
$c = $a + $b; //assign expression value to $c
?>
Numeric operators are used most of the time with infix expressions. That means the operator is usually between two operands. Some numeric operators are unary operators and require one single operand.
In the following examples we consider; $x = 4, $y = 2.
Operator | Name | Expression | Result |
+ | Addition | $x + $y | 6 |
– | Subtraction | $x – $y | 2 |
* | Multiplication | $x * $y | 8 |
/ | Division | $x / $y | 2 |
% | Modulus | $x % $y | 0 |
** | Exponential | $x ** $y | 16 |
Next operators are used to modify in place value of a variable. These operators are a combination of assign operation and a computation operation into one. We use these operators to make expressions shorter but also more performant.
<?php
$a = 8; // declare a number
$a += 2; // execute $a = $a + 2
?>
Operator | Description |
= | Assignment / Initialization |
+= | Addition modifier |
-= | Subtraction modifier |
*= | Multiplication modifier |
/= | Division modifier |
%= | Modulus modifier |
PHP can compare data of different types and make a logical deduction. First it convert the data to a common type then execute the comparison. These operators are used in conditional expressions that produce a Boolean result: true or false.
== | Equal (same value) |
!= | Not equal |
<> | Not equal |
=== | Identical (same value and type) |
!== | Not identical |
> | Greater than |
< | Less than |
>= | Greater than or equal to |
<= | Less than or equal to |
If you know a bit of logic you must also know that logical values are called Boolean values: true and false. For variables having these values we can use special operators, called Boolean operators also known as logical operators. In PHP you can use a symbol or a keyword for making Logical expressions.
Symbol | Keyword | Example |
---|---|---|
&& | and | $a and $b == $a && $b |
|| | or | $a or $b == $a || $b |
^ | xor | $a xor $b == $a ^ $b |
! | not | !$a == not $a |
This operators are similar to logic operators, except they operate on integer numbers, considering 0 = false and 1 = true. Any binary number is actually a set of Boolean values. When you apply a bitwise operation between the two numbers, the operation is executed bit by bit:
Symbol | Description | Example |
---|---|---|
~ | Bitwise not | ~1010 == 0101 |
& | Bitwise and | 1010 | 1100 == 1000 |
| | Bitwise or | 1010 | 1100 == 1110 |
^ | Bitwise xor | 1010 ^ 1100 == 0110 |
Note: Bitwise operators actually work for Booleans due to automatic conversion to integer values.
Variable names in PHP start with $ prefix. PHP is a dynamic language. Type of variable is automatically detected by the PHP engine. In next example we concatenate a string literal with variable using a dot.
<?php
$status = "married";
echo "My status is: " . $status . "<br>";
?>
Note: Statement "echo", will create output for the browser, so it can contain HTML tags.
One very useful feature of PHP is the ability to replace a variable inside a string template without a special notation. The only thing to do is to use double quotes for string to be used as a template.
<?php
$first = 1; // declare a number
$second = 2; // declare second number
echo "\$first = $first \$second = $second";
?>
Output:
$first = 1 $second = 2
Note: You can see inside the string the back-slash "\$first" will prevent interpolation.
PHP can be used in combination with HTML and XML tags. The general idea is, other content in *.php files is ignored if is not enclosed in recognized tags: <?php?>. A cool trick is to use some php and some html using conditionals:
<?php if ($expression == true): ?>
// This will show if the expression is true.
<?php else: ?>
// Otherwise this will show.
<?php endif; ?>
Note: The $expression can be a variable declared in another <?php?> fragment. So your php code can be fragmented into multiple tags but the variables are global, they can be used in any other <?php?> fragment after they are defined.
Actually most control statements offer alternative syntax. This is useful to make PHP code more readable when is entangled with HTML. In next example you can see a bluet list created with alternative syntax for "while" statement:
<p>
<?php $a = 0 ?>
<ul>
<?php while($a < 10): ?>
<li> a = <?= $a?> </li>
<?php $a++;
endwhile;
?>
<ul>
</p>
The short tag <?= $expression ?>
can be used in php files instead of <?php echo $expression ?>
. This is called "short php tag" and is useful when you have a string variable to show immediately in your page.
Read next: Control Flow