Basic PHP Syntax
- A PHP script can be placed anywhere in the document.
- A PHP script starts with
<?phpand ends with?> - The default file extension for PHP files is "
.php". - A PHP file normally contains HTML tags, and some PHP scripting code.
- In PHP, keywords (e.g. if, else, while, echo, etc.), classes, functions, and user-defined functions are not case-sensitive.
My first PHP page
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
-
Comments can be used to:
- Let others understand your code
- Remind yourself of what you did - Most programmers have experienced coming back to their own work a year or two later and having to re-figure out what they did. Comments can remind you of what you were thinking when you wrote the code
-
Examples :
// This is a single-line comment # This is also a single-line comment/* This is a multiple-lines comment block that spans over multiple lines */// You can also use comments to leave out parts of a code line $x = 5 /* + 15 */ + 5; echo $x;
Output
- With PHP, there are two basic ways to get output:
echoandprint. - The differences are small:
echohas no return value whileprinthas a return value of 1 so it can be used in expressions.echocan take multiple parameters (although such usage is rare) whileprintcan take one argument.echois marginally faster thanprint. -
The
echostatement can be used with or without parentheses:echoorecho().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
printstatement can be used with or without parentheses:printorprint().print "<h2>PHP is Fun!</h2>"; print "Hello world!<br>"; print "I'm about to learn PHP!";
PHP Variables
- Variables are "containers" for storing information.
-
In PHP, a variable starts with the
$sign, followed by the name of the variable:
$txt = "Hello world!"; - Unlike other programming languages, PHP has no command for declaring a variable. It is created the moment you first assign a value to it.
-
Rules for PHP variables:
- A variable starts with the
$sign, followed by the name of the variable - A variable name must start with a letter or the underscore character
- A variable name cannot start with a number
- A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
- Variable names are case-sensitive (
$ageand$AGEare two different variables)
- A variable starts with the
-
Example:
$txt = "simple steps"; echo "I love " . $txt . "!"; $x = 5; $y = 4; echo $x + $y;
PHP Constants
- Constants are like variables except that once they are defined they cannot be changed or undefined.
-
To create a constant, use the
define()function.
[define(name, value, case-insensitive)]- name: Specifies the name of the constant
- value: Specifies the value of the constant
-
Example :
define("GREETING", "Welcome to W3Schools.com!"); echo GREETING; -
PHP Constant Arrays
define("cars", [ "Alfa Romeo", "BMW", "Toyota" ]); echo cars[0]; -
Constants are Global
define("GREETING", "Welcome to W3Schools.com!"); function myTest() { echo GREETING; } myTest();
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:
$x = "Hello world!"; $y = 'Hello world!'; -
PHP Integer
An integer data type is a non-decimal number between -2,147,483,648 and 2,147,483,647.
Rules for integers:- An integer must have at least one digit
- An integer must not have a decimal point
- An integer can be either positive or negative
- Integers can be specified in: decimal (base 10), hexadecimal (base 16), octal (base 8), or binary (base 2) notation
$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. -
PHP Boolean
A Boolean represents two possible states: true or false. -
PHP array
An array stores multiple values in one single variable.
$cars = array("Volvo","BMW","Toyota"); var_dump($cars); -
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.
If a variable is created without a value, it is automatically assigned a value of NULL.$x = "Hello world!"; $x = null; var_dump($x);
PHP Integers
-
2, 256, -256, 10358, -179567 are all integers.
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. -
Here are some rules for integers:
- An integer must have at least one digit
- An integer must NOT have a decimal point
- An integer can be either positive or negative
- Integers can be specified in three formats: decimal (10-based), hexadecimal (16-based - prefixed with 0x) or octal (8-based - prefixed with 0)
-
PHP has the following predefined constants for integers:
PHP_INT_MAX- The largest integer supportedPHP_INT_MIN- The smallest integer supportedPHP_INT_SIZE- The size of an integer in bytes
-
PHP has the following functions to check if the type of a variable is integer:
is_int() -
Example :
$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.
2.0, 256.4, 10.358, 7.64E+5, 5.56E-5 are all floats.
The float data type can commonly store a value up to 1.7976931348623E+308 (platform dependent), and have a maximum precision of 14 digits.
-
PHP has the following predefined constants for floats (from PHP 7.2):
PHP_FLOAT_MAX- The largest representable floating point numberPHP_FLOAT_MIN- The smallest representable positive floating point number-PHP_FLOAT_MAX- The smallest representable negative floating point numberPHP_FLOAT_DIG- The number of decimal digits that can be rounded into a float and back without precision lossPHP_FLOAT_EPSILON- The smallest representable positive number x, so that x + 1.0 != 1.0
-
PHP has the following functions to check if the type of a variable is float:
is_float() -
Example :
$x = 10.365; var_dump(is_float($x));
PHP Infinity
- A numeric value that is larger than
PHP_FLOAT_MAXis considered infinite. -
PHP has the following functions to check if a numeric value is finite or infinite:
is_finite()is_infinite()
-
Example:
$x = 1.9e411; var_dump($x);
PHP NaN
- NaN stands for Not a Number.
-
PHP has the following functions to check if a value is not a number:
is_nan() -
Example:
$x = acos(8); var_dump($x);
PHP Numerical Strings
- The PHP
is_numeric()function can be used to find whether a variable is numeric. The function returns true if the variable is a number or a numeric string, false otherwise. -
Example:
$x = 5985; var_dump(is_numeric($x)); $x = "5985"; var_dump(is_numeric($x)); $x = "59.85" + 100; var_dump(is_numeric($x)); $x = "Hello"; var_dump(is_numeric($x));
PHP Casting Strings and Floats to Integers
- Sometimes you need to cast a numerical value into another data type.
- The (int), (integer), or intval() function are often used to convert a value to an integer.
-
// Cast float to int $x = 23465.768; $int_cast = (int)$x; echo $int_cast; // Cast string to int $x = "23465.768"; $int_cast = (int)$x; echo $int_cast;
PHP Math
-
PHP has a set of math functions that allows you to perform mathematical tasks on numbers.
Function Description Example pi() The pi() function returns the value of PI echo(pi()); // returns 3.1415926535898min() and max() The min() and max() functions can be used to find the lowest or highest value in a list of arguments echo(min(0, 150, 30, 20, -8, -200)); // returns -200 echo(max(0, 150, 30, 20, -8, -200)); // returns 150abs() The abs() function returns the absolute (positive) value of a number echo(abs(-6.7)); // returns 6.7sqrt() The sqrt() function returns the square root of a number echo(sqrt(64)); // returns 8round() The round() function rounds a floating-point number to its nearest integer echo(round(0.60)); // returns 1 echo(round(0.49)); // returns 0rand()
rand(min,max)The rand() function generates a random number: echo(rand());sin() & cos() & tan() Returns the sine and cosine and tan of a number
value in radianspow() Returns x raised to the power of y rad2deg() Converts a radian value to a degree value
PHP Operators
-
Arithmetic Operators
operator Description EX (+) Addition $x + $y(-) Subtraction $x - $y(*) Multiplication $x * $y(**) Exponentiation $x ** $y(/) Division $x / $y(%) Modulus (Remainder) $x % $y -
Assignment Operators
operator Expression Same As EX (=) x = y x = y $x = 10(+=) x += y x = x + y $x += 5;(-=) x -= y x = x - y $x -= 5;(*=) x *= y x = x * y $x *= 5;(/=) x /= y x = x / y $x /= 5;(%=) x %= y x = x % y $x %= 5; -
Comparison Operators
Comparison operators are used in logical statements to determine equality or difference between variables or values.
Operator Description Comparing Returns (==) equal to $x == 8false $x == 5true $x == "5"true (===) equal value and equal type $x === 5true $x === "5"false (!=) not equal $x != 8true (!=) not equal $x <> 8true (!==) not equal value or not equal type $x !== 5false $x !== "5"true $x !== 8true (>) greater than $x > 8false (<) less than $x < 8true (>=) greater than or equal to $x >= 8false (<=) less than or equal to $x <= 8true -
Increment / Decrement Operators
The PHP increment operators are used to increment a variable's value.
The PHP decrement operators are used to decrement a variable's value.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 -
Logical Operators
Logical operators are used to determine the logic between variables or values.
Operator Description Example && and ($x < 10 && $y > 1) is true and and ($x < 10 and $y > 1) is true || or ($x == 5 || $y == 5) is false or or ($x == 5 or $y == 5) is false ! not !(x == y) is true xor xor $x xor $y -
String Operators
the . operator used to add string "concatenate"
EX:
$txt1 = "Hello"; $txt2 = " world!"; echo $txt1 . $txt2;