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. The modern coding standards are contained in PSR-1 (Basic Coding Standard) and PSR-2 (Coding Style Guide).
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.
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 "</script>" (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:
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:
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:
Elvis operator
… excerpt ends here. Continue reading the full article.
