ArticleslgStudy

science

PHP syntax and semantics

PHP syntax and semantics is a science topic covered in the lgStudy science library. This page brings together a partial reference excerpt, illustrations, worked examples, real-world applications and a short study plan, so you can understand PHP syntax and semantics rather than just read about it. In short: 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.

Key takeaways

  • PHP syntax and semantics belongs to science; place it in that map before memorising details.
  • Learn the definition first, then one example that makes the definition concrete.
  • Connect PHP syntax and semantics to a quantity you can measure, compute or draw — that is where exam questions come from.
  • Reproduce the core statement of PHP syntax and semantics from memory before moving on to harder problems.

Reference excerpt

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.

Worked examples

Example 1 — a first encounter with PHP syntax and semantics

Start with the simplest possible case. Write down what PHP syntax and semantics claims or describes in one sentence, then invent the smallest concrete situation in which that sentence is true. In science, the smallest case is usually a single object, a single equation or a single measurement. Check that every symbol or term in your sentence has a meaning in that case.

Example 2 — changing one variable

Take the situation from Example 1 and change exactly one quantity: double it, halve it, or set it to zero. Predict what should happen to PHP syntax and semantics before you calculate. Comparing your prediction with the result is the fastest way to find out whether you understand the idea or only the words.

Example 3 — an exam-style question

Typical questions about PHP syntax and semantics ask you to (a) state it precisely, (b) apply it to given data, and (c) explain a limitation. Practise writing all three answers in under five minutes; the third part is what separates a full-mark answer from an average one.

Applications of PHP syntax and semantics

In research
PHP syntax and semantics appears in science research whenever the underlying quantities have to be modelled precisely. Papers usually cite it as a starting assumption and then explore where it breaks down.
In technology and industry
Engineering practice reuses PHP syntax and semantics in design rules, simulations and safety margins. Knowing the idea lets you read a specification sheet and understand why the numbers look the way they do.
In the classroom
PHP syntax and semantics is common in secondary-school and first-year university syllabi. It links to neighbouring topics PHP, Programming language syntax, so understanding it makes those chapters shorter.
In everyday life
Look for PHP syntax and semantics outside the textbook — in sport, cooking, traffic, electronics or the sky above you. An example you found yourself is remembered far longer than one you were given.

Affiliate

Preply — study more efficiently by working with a personal tutor. 50% off.

How to study PHP syntax and semantics in 20 minutes

  1. Read the reference excerpt below once, without taking notes.
  2. Close the page and write down what PHP syntax and semantics means in your own words.
  3. Compare your version with the excerpt and mark what you missed.
  4. Work through the three examples above with pen and paper.
  5. Explain PHP syntax and semantics out loud to somebody else — or to Teacher Smith in the lgStudy chat.

Frequently asked questions

What is PHP syntax and semantics in simple terms?

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.

Why does PHP syntax and semantics matter?

Because it connects several science ideas at once: it gives you a definition you can apply, a quantity you can calculate, and a way to check whether a result is plausible.

How should I study PHP syntax and semantics?

Read the excerpt, restate it from memory, then work through the examples and applications listed on this page. The five-step study plan above takes about twenty minutes.

What does this page cover?

It gives you a compact reference excerpt plus original lgStudy explanations, examples, applications and study material on PHP syntax and semantics.

Tags

  • PHP
  • Programming language syntax

Keep exploring