The syntax and semantics of PHP, a programming language, form a set of rules that define how a PHP program can be written and interpreted.
Historically, the development of PHP has been somewhat haphazard. To counter this, the PHP Framework Interop Group (FIG) has created The PHP Standards Recommendation (PSR) documents that have helped bring more standardization to the language since 2009. The modern coding standards are contained in PSR-1 (Basic Coding Standard) and PSR-2 (Coding Style Guide).
Some keywords represent things that look like functions, some look like constants, but they are actually language constructs. It is forbidden to use any keywords as constants, class names, functions (with the exception of <code>readonly</code>) or methods. Using them as variable names is allowed, but it can be confusing.
PHP generally follows C syntax, with exceptions and enhancements for its main use in web development, which makes heavy use of string manipulation. PHP variables must be prefixed by "<code>$</code>". This allows PHP to perform string interpolation in double quoted strings, where backslash is supported as an escape character. No escaping or interpolation is done on strings delimited by single quotes. PHP also supports a C-like sprintf function. Code can be modularized into functions defined with keyword <code>function</code>. PHP supports an optional object oriented coding style, with classes denoted by the <code>class</code> keyword. Functions defined inside classes are sometimes called methods. Control structures include: <code>if</code>, <code>while</code>, <code>do/while</code>, <code>for</code>, <code>foreach</code>, and <code>switch</code>. Statements are terminated by a semicolon, not line endings.
The PHP processor only parses code within its delimiters. Anything outside its delimiters is sent directly to the output and not parsed by PHP. The only open/close delimiters allowed by PSR-1 are "" and "" or and .
The purpose of the delimiting tags is to separate PHP code from non-PHP data (mainly HTML). Although rare in practice, PHP will execute code embedded in any file passed to its interpreter, including binary files such as PDF or JPEG files, or in server log files. Everything outside the delimiters is ignored by the PHP parser and is passed through as output.
These recommended delimiters create correctly formed XHTML and other XML documents. This may be helpful if the source code documents ever need to be processed in other ways during the life of the software.
If proper XML validation is not an issue, and a file contains only PHP code, it is preferable to omit the PHP closing (<code>?></code>) tag at the end of the file.
Other delimiters can be used on some servers, though most are no longer supported. Examples are:
Variables are prefixed with a dollar sign and a type does not need to be specified in advance. Unlike function and class names, variable names are case-sensitive. Both double-quoted (<code>""</code>) and heredoc strings allow the ability to embed a variable's value into the string. As in C, variables may be cast to a specific type by prefixing the type in parentheses. PHP treats newlines as whitespace, in the manner of a free-form language. The concatenation operator is <code>.</code> (dot). Array elements are accessed and set with square brackets in both associative arrays and indexed arrays. Curly brackets can be used to access array elements, but not to assign.
<code>$this</code> cannot be used as a variable name because it is a pseudovariable used in objects to access a method of the current object.
PHP has three types of comment syntax: <code>/* */</code> which serves as block comments, and <code>//</code> as well as <code>#</code> which are used for inline comments. Many examples use the <code>print</code> function instead of the <code>echo</code> function. Both functions are nearly identical; the major difference being that <code>print</code> is slower than <code>echo</code> because the former will return a status indicating if it was successful or not in addition to text to output, whereas the latter does not return a status and only returns the text for output.
The usual "Hello World" code example for PHP is:
The example above outputs the following: <pre> Hello World! </pre> Instead of using and the statement, an optional "shortcut" is the use of instead of which implicitly echoes data. For example:
The above example also illustrates that text not contained within enclosing PHP tags will be directly output.
PHP supports arithmetic operators, assignment operators, bitwise operators, comparison operators, error control operators, execution operators, increment/decrement operators, logical operators, string operators, array operators, and .
Addition, subtraction, multiplication, and division are expressed using <code>+</code>, <code>-</code>, <code>*</code>, and <code>/</code> operators (respectively), modulus with <code>%</code>, exponentiation with <code>**</code>, and increment and decrement with <code>++</code> and <code>--</code> (respectively).
Concatenation is expressed with <code>.</code>, and appending text to an existing string is represented as <code>.=</code>.
<code>==</code> compares two values and outputs <code>true</code> if their values are equal. <code>!=</code> or <code><></code> compares if their values are not equal. <code>===</code> and <code>!==</code> compare if both their value and the data types are equal.
<code><</code> and <code>></code> represent less than and greater than, respectively. <code><=</code> and <code>>=</code> represent less than or equal and greater than or equal, respectively.
The spaceship operator (<code><=></code>), introduced in PHP 7, compares the values to the left and the right of the operator. If they are equal, it outputs <code>0</code>, if the value on the left is greater, <code>1</code>, and if the value on the right is greater, <code>-1</code>.
<code>&&</code> or <code>and</code> represents logical conjunction, and <code>||</code> or <code>or</code> represents logical disjunction. <code>!</code> represents logical negation, and cannot be substituted with <code>not</code>.
Ternary operators are a shorthand for <code>if... else</code> statements that evaluates a condition, and provides two values, one to use if the condition is true and the other if the condition is false. They are in the format <code>condition ? action_if_true : action_if_false</code>. For example:
Since PHP 5.3, PHP supports the Elvis operator (<code>?:</code>), in which it is possible to omit the middle part of the ternary operator.
Since version 7.0, PHP supports the null coalescing operator (<code>??</code>).
Since version 7.4, PHP also supports the null coalescing operator with the <code>??=</code> syntax.
Since version 8.0 PHP also supports the safe navigation operator (<code>?-></code>).
The syntax of a PHP if ... else statement is as follows:
For single statements, the brackets may be omitted and the if optionally condensed to a single line:
An example of the syntax of a PHP switch statement is as follows:
Note that unlike in C, values in case statement can be any type, not just integers.
PHP 8 introduces the expression. The match expression is conceptually similar to a statement and is more compact for some use cases. statements are traditionally favored for simple value-based comparisons, statements provide more flexibility and readability, particularly when using in complex conditions or patterns.
The PHP syntax of a for loop is as follows:
The syntax for a PHP while loop is as follows:
A PHP do while loop executes statements at least once. For example:
The syntax for a PHP foreach loop loop is as follows:
PHP offers an alternative syntax using colons rather than the standard curly-brace syntax (of "<code>{...}</code>"). This syntax affects the following control structures: <code>if</code>, <code>while</code>, <code>for</code>, <code>foreach</code>, and <code>switch</code>. The syntax varies only slightly from the curly-brace syntax. In each case the opening brace (<code>{</code>) is replaced with a colon (<code>:</code>) and the close brace is replaced with <code>endif;</code>, <code>endwhile;</code>, <code>endfor;</code>, <code>endforeach;</code>, or <code>endswitch;</code>, respectively. Mixing syntax styles within the same control block is not supported. An example of the syntax for an <code>if</code>/<code>elseif</code> statement is as follows:
This style is sometimes called template syntax, as it is often found easier to read when combining PHP and HTML or JavaScript for conditional output:
Runtime exception handling method in PHP is inherited from C++.
PHP supports four scalar types: <code>bool</code>, <code>int</code>, <code>float</code>, <code>string</code>.
PHP has a native Boolean type, named "<code>bool</code>", similar to the native Boolean types in Java and C++. Using the Boolean type conversion rules, non-zero values are interpreted as <code>true</code> and zero as <code>false</code>, as in Perl. Both constants <code>true</code> and <code>false</code> are case-insensitive.
PHP stores whole numbers in a platform-dependent range. This range is typically that of 32-bit or 64-bit signed integers. Integer variables can be assigned using decimal (positive and negative), octal, hexadecimal, and binary notations.
Real numbers are also stored in a platform-specific range. They can be specified using floating point notation, or two forms of scientific notation.
PHP supports <code>strings</code>, which can be used with single quotes, double quotes, nowdoc or heredoc syntax.
Double quoted strings support variable interpolation:
Curly braces syntax:
PHP supports two special types: <code>null</code>, <code>resource</code>. The <code>null</code> data type represents a variable that has no value. The only value in the <code>null</code> data type is NULL. The NULL constant is not case sensitive. Variables of the "<code>resource</code>" type represent references to resources from external sources. These are typically created by functions from a particular extension, and can only be processed by functions from the same extension. Examples include file, image and database resources.
PHP supports four compound types: <code>array</code>, <code>object</code>, <code>callable</code>, <code>iterable</code>.
Arrays can contain mixed elements of any type, including resources, objects. Multi-dimensional arrays are created by assigning arrays as array elements. PHP has no true array type. PHP arrays are natively sparse and associative. Indexed arrays are simply hashes using integers as keys.
Indexed array:
Associative array:
Multidimensional array:
The <code>object</code> data type is a combination of variables, functions and data structures in the object-oriented programming paradigm.
Since version 5.3 PHP has first-class functions that can be used e.g. as an argument to another function.
<code>Iterable</code> type indicate that variable can be used with <code>foreach</code> loop. It can be any <code>array</code> or <code>generator</code> or object that implementing the special internal <code>Traversable</code> interface.
Union types were introduced in PHP 8.0.
PHP attempts to convert values to the expected data type when it encounters an unexpected data type. This is known as type juggling. PHP throws a <code>TypeError</code> if the value cannot be interpreted.
PHP treats any string that contains the value of an integer as an integer in arithmetic operations, and does the same for floats. When a string starts with an integer or float followed by other characters (e.g. <code>'5star'</code>), PHP ignores the later characters and treats the value as <code>5</code>. When a string does not start with an integer or float, it is treated as 0.
In string operations, PHP treats values as strings. It also treats <code>true</code> as <code>'1'</code>, and <code>false</code> as <code></code>.
In logical operations, PHP treats values as booleans. Specifically, PHP treats <code>0</code>, <code>0.0</code>, <code>'0'</code>, <code></code>, <code>array[]</code>, and <code>null</code> as <code>false</code>, and any other value is treated as <code>true</code>.
In comparative operations, PHP treats <code>null</code> as <code>""</code> when the second argument is a string. When the first argument is a boolean or <code>null</code>, it converts both arguments to a boolean. Objects and arrays are always treated as greater than non-objects or arrays, respectively.
PHP has hundreds of base functions and thousands more from extensions. Prior to PHP version 5.3.0, functions are not first-class functions and can only be referenced by their name, whereas PHP 5.3.0 introduces closures. User-defined functions can be created at any time and without being prototyped. Functions can be defined inside code blocks, permitting a run-time decision as to whether or not a function should be defined. There is no concept of local functions. Function calls must use parentheses with the exception of zero argument class constructor functions called with the PHP <code>new</code> operator, where parentheses are optional.
An example function definition is the following:
Function calls may be made via variables, where the value of a variable contains the name of the function to call. This is illustrated in the following example:
A default value for parameters can be assigned in the function definition, but prior to PHP 8.0 did not support named parameters or parameter skipping. Some core PHP developers have publicly expressed disappointment with this decision. Others have suggested workarounds for this limitation.
Named arguments were introduced in PHP 8.0. They are in the format <code>param_name: value</code> and allow arguments to be given in any order. For example:
Specifying the types of function parameters and function return values has been supported since PHP 7.0.
Return type declaration:
Parameters typing:
Strict typing is enabled with <code>declare(strict_types = 1);</code>. In strict typing, type juggling is disabled and a <code>TypeError</code> is raised when types mismatch or if a function returns the wrong data type. For example:
Without strict typing enabled:
With strict typing enabled:
PHP supports true anonymous functions as of version 5.3. In previous versions, PHP only supported quasi-anonymous functions through the <code>create_function()</code> function.
Since version 7.4 PHP also supports arrow functions syntax (<code>=></code>).
Creating closures
using
Using generators, we can write code that uses foreach to iterate over a dataset without having to create an array in memory, which can result in memory overhead or significant processing time for generation.
Basic object-oriented programming functionality was added in PHP 3. Object handling was completely rewritten for PHP 5, expanding the feature set and enhancing performance. In previous versions of PHP, objects were handled like primitive types. The drawback of this method was that the whole object was copied when a variable was assigned or passed as a parameter to a method. In the new approach, objects are referenced by handle, and not by value. PHP 5 introduced private and protected member variables and methods, along with abstract classes and final classes as well as abstract methods and final methods. It also introduced a standard way of declaring constructors and destructors, similar to that of other object-oriented languages such as C++, and a standard exception handling model. Furthermore PHP 5 added Interfaces and allows for multiple Interfaces to be implemented. There are special interfaces that allow objects to interact with the runtime system. Objects implementing ArrayAccess can be used with array syntax and objects implementing Iterator or IteratorAggregate can be used with the foreach language construct. The static method and class variable features in Zend Engine 2 do not work the way some would expect. There is no virtual table feature in the engine, so static variables are bound with a name instead of a reference at compile time.
This example shows how to define a class, <code>Foo</code>, that inherits from class <code>Bar</code>. The method <code>myStaticMethod</code> is a public static method that can be called with <code>Foo::myStaticMethod();</code>.
If the developer creates a copy of an object using the reserved word clone, the Zend Engine will check if a <code>__clone()</code> method has been defined or not. If not, it will call a default <code>__clone()</code> which will copy the object's properties. If a <code>__clone()</code> method is defined, then it will be responsible for setting the necessary properties in the created object. For convenience, the engine will supply a function that imports the properties of the source object, so that the programmer can start with a by-value of the source object and only override properties that need to be changed.