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.

Overview

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.PSR-Huh? The modern coding standards are contained in PSR-1 (Basic Coding Standard)PSR-1 and PSR-2 (Coding Style Guide).PSR-2 Keywords 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 readonly) or methods. Using them as variable names is allowed, but it can be confusing.PHP: List of Keywords - Manual

__halt_compiler() abstract and array() as break callable (as of PHP 5.4) 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 (as of PHP 5.5) fn (as of PHP 7.4) for foreach function global goto (as of PHP 5.3) if implements include include_once instanceof insteadof (as of PHP 5.4) interface isset() list() match (as of PHP 8.0) namespace (as of PHP 5.3) new or print private protected public readonly (as of PHP 8.1.0) require require_once return static switch throw trait (as of PHP 5.4) try unset() use var while xor yield (as of PHP 5.5) yield from (as of PHP 7.0)

Basic language constructs

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 "$". 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 function. PHP supports an optional object oriented coding style, with classes denoted by the class keyword. Functions defined inside classes are sometimes called methods. Control structures include: if, while, do/while, for, foreach, and switch. Statements are terminated by a semicolon, not line endings.

Delimiters

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 "<?php" 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 (?>) tag at the end of the file.

Non-recommended tags

Other delimiters can be used on some servers, though most are no longer supported. Examples are:

"<script language="php">" and "<code></script></code>" (removed in PHP7) Short opening tags (<?) (configured with the short_open_tag ini setting) A special form of the <? tag is <?=, which automatically echos the next statement. Prior to PHP 5.4.0 this was also controlled with short_open_tag, but is always available in later versions. ASP style tags (<% or <%=) (removed in PHP7)

Variables and comments 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 ("") 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 . (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.

$this 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: /* */ which serves as block comments, and // as well as # which are used for inline comments. Many examples use the print function instead of the echo function. Both functions are nearly identical; the major difference being that print is slower than echo 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.

Simplest program

The usual "Hello World" code example for PHP is:

<?php echo "Hello World!\n"; ?>

The example above outputs the following: Hello World! Instead of using <?php and the echo statement, an optional "shortcut" is the use of <?= instead of <?php which implicitly echoes data. For example: <!DOCTYPE html> <html> <head> <title>PHP "Hello, World!" program</title> </head> <body> <p><?="Hello World!"?></p> </body> </html>

The above example also illustrates that text not contained within enclosing PHP tags will be directly output.

Operators

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 conditional assignment operators.

Arithmetic and string operators Addition, subtraction, multiplication, and division are expressed using +, -, *, and / operators (respectively), modulus with %, exponentiation with **, and increment and decrement with ++ and -- (respectively).

Concatenation is expressed with ., and appending text to an existing string is represented as .=.

Comparison operators == compares two values and outputs true if their values are equal. != or <> compares if their values are not equal. === and !== compare if both their value and the data types are equal.

< and > represent less than and greater than, respectively. <= and >= represent less than or equal and greater than or equal, respectively.

The spaceship operator (<=>), introduced in PHP 7, compares the values to the left and the right of the operator. If they are equal, it outputs 0, if the value on the left is greater, 1, and if the value on the right is greater, -1.

Logical operators && or and represents logical conjunction, and || or or represents logical disjunction. ! represents logical negation, and cannot be substituted with not.

Conditional operators

Ternary operator

Ternary operators are a shorthand for if... else 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 condition ? action_if_true : action_if_false. For example: <?php $num = 5; $message = $num < 5 ? "$num is less than 5" : "$num is not less than 5" ?> <!DOCTYPE html> <html> <head> <title>PHP: Ternary operators</title> </head> <body> <h1>PHP: Ternary operators</h1> <p><?= $message ?></p> </body> </html>

Elvis operator

Since PHP 5.3, PHP supports the Elvis operator (?:), in which it is possible to omit the middle part of the ternary operator.

$c = $a ?: $b;

/* Equivalent to */

$c = $a ? $a : $b;

Null coalescing operator

Since version 7.0, PHP supports the null coalescing operator (??). $a = $b ?? $c;

/* Equivalent to */

$a = isset($b) ? $b : $c; Since version 7.4, PHP also supports the null coalescing operator with the ??= syntax. $a ??= $b;

/* Equivalent to */

$a = $a ?? $b;

Safe navigation operator

Since version 8.0 PHP also supports the safe navigation operator (?->). $variable = $object?->method();

/* Equivalent to */

$variable = $object !== null ? $object->method() : null;

Control structures

Conditionals

If ... else statement The syntax of a PHP if ... else statement is as follows:

if (condition) { // statements; } elseif (condition2) { // statements; } else { // statements; }

For single statements, the brackets may be omitted and the if optionally condensed to a single line:

if (condition) dosomething(); elseif (condition2) dosomethingelse(); else doyetathirdthing();

Switch statement

An example of the syntax of a PHP switch statement is as follows:

switch (expr) { case 0: // statements; break; case 1: // statements; break; case 2: // statements; break; default: // statements; }

Note that unlike in C, values in case statement can be any type, not just integers.

Match expression 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. echo match (1) { 0 => 'Foo', 1 => 'Bar', 2 => 'Baz', }; //> Bar

Loops

For loop

The PHP syntax of a for loop is as follows:

for (initialization; condition; update) { // statements; }

While loop

The syntax for a PHP while loop is as follows:

while (condition) { // statements; }

Do while loop

A PHP do while loop executes statements at least once. For example:

do { // statements; } while (condition);

Foreach loop

The syntax for a PHP foreach loop is as follows:

foreach ($set as $value) { // statements; }

Alternative syntax for control structures PHP offers an alternative syntax using colons rather than the standard curly-brace syntax (of "{...}"). This syntax affects the following control structures: if, while, for, foreach, and switch. The syntax varies only slightly from the curly-brace syntax. In each case the opening brace ({) is replaced with a colon (:) and the close brace is replaced with endif;, endwhile;, endfor;, endforeach;, or endswitch;, respectively. Mixing syntax styles within the same control block is not supported. An example of the syntax for an if/elseif statement is as follows:

if (condition): // code here elseif (condition): // code here else: // code here endif;

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:

<html> <?php if ($day == 'Thursday'): ?> <div>Tomorrow is Friday!</div> <?php elseif ($day == 'Friday'): ?> <div>TGIF</div> <?php else: ?> <div>ugh</div> <?php endif; ?> </html>

Exception handling

Runtime exception handling method in PHP is inherited from C++.

function inv($x) { if ($x == 0) { throw new Exception('Division by zero');

return 1 / $x; }

try { echo inv(2); // prints 0.5 echo inv(0); // throw an exception echo inv(5); // will not run } catch (Exception $e) { echo $e->getMessage(); // prints Division by zero }

// Continue execution echo "Hello"; // prints Hello

Data types Scalar types

PHP supports four scalar types: bool, int, float, string.

Boolean

PHP has a native Boolean type, named "bool", similar to the native Boolean types in Java and C++. Using the Boolean type conversion rules, non-zero values are interpreted as true and zero as false, as in Perl. Both constants true and false are case-insensitive.

Integer