Operators An operator is something that takes one or more values (or expressions, in programming jargon) and yields another value (so that the construction itself becomes an expression). Operators can be grouped according to the number of values they take. Unary operators take only one value, for example ! (the logical not operator) or ++ (the increment operator). Binary operators take two values, such as the familiar arithmetical operators + (plus) and - (minus), and the majority of PHP operators fall into this category. Finally, there is a single ternary operator, ? :, which takes three values; this is usually referred to simply as "the ternary operator" (although it could perhaps more properly be called the conditional operator). A full list of PHP operators follows in the section Operator Precedence. The section also explains operator precedence and associativity, which govern exactly how expressions containing several different operators are evaluated. Operator Precedence The precedence of an operator specifies how "tightly" it binds two expressions together. For example, in the expression 1 + 5 * 3, the answer is 16 and not 18 because the multiplication ("*") operator has a higher precedence than the addition ("+") operator. Parentheses may be used to force precedence, if necessary. For instance: (1 + 5) * 3 evaluates to 18. When operators have equal precedence their associativity decides how the operators are grouped. For example "-" is left-associative, so 1 - 2 - 3 is grouped as (1 - 2) - 3 and evaluates to -4. "=" on the other hand is right-associative, so $a = $b = $c is grouped as $a = ($b = $c). Operators of equal precedence that are non-associative cannot be used next to each other, for example 1 < 2 > 1 is illegal in PHP. The expression 1 <= 1 == 1 on the other hand is legal, because the == operator has a lower precedence than the <= operator. Associativity is only meaningful for binary (and ternary) operators. Unary operators are either prefix or postfix so this notion is not applicable. For example !!$a can only be grouped as !(!$a). Use of parentheses, even when not strictly necessary, can often increase readability of the code by making grouping explicit rather than relying on the implicit operator precedence and associativity. The following table lists the operators in order of precedence, with the highest-precedence ones at the top. Operators on the same line have equal precedence, in which case associativity decides grouping. Operator Precedence Associativity Operators Additional Information (n/a) clone new clone and new right ** arithmetic (n/a) + - ++ -- ~ (int) (float) (string) (array) (object) (bool) @ arithmetic (unary + and -), increment/decrement, bitwise, type casting&listendand; error control left instanceof type (n/a) ! logical left * / % arithmetic left + - . arithmetic (binary + and -), array&listendand; string (. prior to PHP 8.0.0) left << >> bitwise left . string (as of PHP 8.0.0) non-associative < <= > >= comparison non-associative == != === !== <> <=> comparison left & bitwise&listendand; references left ^ bitwise left | bitwise left && logical left || logical right ?? null coalescing non-associative ? : ternary (left-associative prior to PHP 8.0.0) right = += -= *= **= /= .= %= &= |= ^= <<= >>= ??= assignment (n/a) yield from yield from (n/a) yield yield (n/a) print print left and logical left xor logical left or logical
Associativity $a = 5, $b = 5 ?> ]]> Operator precedence and associativity only determine how expressions are grouped, they do not specify an order of evaluation. PHP does not (in the general case) specify in which order an expression is evaluated and code that assumes a specific order of evaluation should be avoided, because the behavior can change between versions of PHP or depending on the surrounding code. Undefined order of evaluation ]]> <literal>+</literal>, <literal>-</literal> and <literal>.</literal> have the same precedence (prior to PHP 8.0.0) ]]> &example.outputs; Although = has a lower precedence than most other operators, PHP will still allow expressions similar to the following: if (!$a = foo()), in which case the return value of foo() is put into $a. &reftitle.changelog; &Version; &Description; 8.0.0 String concatenation (.) now has a lower precedence than arithmetic addition/subtraction (+ and -) and bitwise shift left/right (<< and >>); previously it had the same precedence as + and - and a higher precedence than << and >>. 8.0.0 The ternary operator (? :) is non-associative now; previously it was left-associative. 7.4.0 Relying on the precedence of string concatenation (.) relative to arithmetic addition/subtraction (+ or -) or bitwise shift left/right (<< or >>), i.e. using them together in an unparenthesized expression, is deprecated. 7.4.0 Relying on left-associativity of the ternary operator (? :), i.e. nesting multiple unparenthesized ternary operators, is deprecated.
Arithmetic Operators Remember basic arithmetic from school? These work just like those. Arithmetic Operators Example Name Result +$a Identity Conversion of $a to int or float as appropriate. -$a Negation Opposite of $a. $a + $b Addition Sum of $a and $b. $a - $b Subtraction Difference of $a and $b. $a * $b Multiplication Product of $a and $b. $a / $b Division Quotient of $a and $b. $a % $b Modulo Remainder of $a divided by $b. $a ** $b Exponentiation Result of raising $a to the $b'th power.
The division operator ("/") returns a float value unless the two operands are integers (or strings that get converted to integers) and the numbers are evenly divisible, in which case an integer value will be returned. For integer division, see intdiv. Operands of modulo are converted to int before processing. For floating-point modulo, see fmod. The result of the modulo operator % has the same sign as the dividend — that is, the result of $a % $b will have the same sign as $a. For example: ]]> &reftitle.seealso; Math functions
Assignment Operators The basic assignment operator is "=". Your first inclination might be to think of this as "equal to". Don't. It really means that the left operand gets set to the value of the expression on the right (that is, "gets set to"). The value of an assignment expression is the value assigned. That is, the value of "$a = 3" is 3. This allows you to do some tricky things: ]]> In addition to the basic assignment operator, there are "combined operators" for all of the binary arithmetic, array union and string operators that allow you to use a value in an expression and then set its value to the result of that expression. For example: ]]> Note that the assignment copies the original variable to the new one (assignment by value), so changes to one will not affect the other. This may also have relevance if you need to copy something like a large array inside a tight loop. An exception to the usual assignment by value behaviour within PHP occurs with objects, which are assigned by reference. Objects may be explicitly copied via the clone keyword. Assignment by Reference Assignment by reference is also supported, using the "$var = &$othervar;" syntax. Assignment by reference means that both variables end up pointing at the same data, and nothing is copied anywhere. Assigning by reference ]]> The new operator returns a reference automatically, as such assigning the result of new by reference is an error. ]]> &example.outputs; More information on references and their potential uses can be found in the References Explained section of the manual. Arithmetic Assignment Operators Example Equivalent Operation $a += $b $a = $a + $b Addition $a -= $b $a = $a - $b Subtraction $a *= $b $a = $a * $b Multiplication $a /= $b $a = $a / $b Division $a %= $b $a = $a % $b Modulus $a **= $b $a = $a ** $b Exponentiation Bitwise Assignment Operators Example Equivalent Operation $a &= $b $a = $a & $b Bitwise And $a |= $b $a = $a | $b Bitwise Or $a ^= $b $a = $a ^ $b Bitwise Xor $a <<= $b $a = $a << $b Left Shift $a >>= $b $a = $a >> $b Right Shift Other Assignment Operators Example Equivalent Operation $a .= $b $a = $a . $b String Concatenation $a ??= $b $a = $a ?? $b Null Coalesce &reftitle.seealso; arithmetic operators bitwise operators null coalescing operator Bitwise Operators Bitwise operators allow evaluation and manipulation of specific bits within an integer. Bitwise Operators Example Name Result $a & $b And Bits that are set in both $a and $b are set. $a | $b Or (inclusive or) Bits that are set in either $a or $b are set. $a ^ $b Xor (exclusive or) Bits that are set in $a or $b but not both are set. ~ $a Not Bits that are set in $a are not set, and vice versa. $a << $b Shift left Shift the bits of $a $b steps to the left (each step means "multiply by two") $a >> $b Shift right Shift the bits of $a $b steps to the right (each step means "divide by two")
Bit shifting in PHP is arithmetic. Bits shifted off either end are discarded. Left shifts have zeros shifted in on the right while the sign bit is shifted out on the left, meaning the sign of an operand is not preserved. Right shifts have copies of the sign bit shifted in on the left, meaning the sign of an operand is preserved. Use parentheses to ensure the desired precedence. For example, $a & $b == true evaluates the equivalency then the bitwise and; while ($a & $b) == true evaluates the bitwise and then the equivalency. If both operands for the &, | and ^ operators are strings, then the operation will be performed on the ASCII values of the characters that make up the strings and the result will be a string. In all other cases, both operands will be converted to integers and the result will be an integer. If the operand for the ~ operator is a string, the operation will be performed on the ASCII values of the characters that make up the string and the result will be a string, otherwise the operand and the result will be treated as integers. Both operands and the result for the << and >> operators are always treated as integers. PHP's error_reporting ini setting uses bitwise values, providing a real-world demonstration of turning bits off. To show all errors, except for notices, the php.ini file instructions say to use: E_ALL & ~E_NOTICE This works by starting with E_ALL: 00000000000000000111011111111111 Then taking the value of E_NOTICE... 00000000000000000000000000001000 ... and inverting it via ~: 11111111111111111111111111110111 Finally, it uses AND (&) to find the bits turned on in both values: 00000000000000000111011111110111 Another way to accomplish that is using XOR (^) to find bits that are on in only one value or the other: E_ALL ^ E_NOTICE error_reporting can also be used to demonstrate turning bits on. The way to show just errors and recoverable errors is: E_ERROR | E_RECOVERABLE_ERROR This process combines E_ERROR 00000000000000000000000000000001 and 00000000000000000001000000000000 using the OR (|) operator to get the bits turned on in either value: 00000000000000000001000000000001 Bitwise AND, OR and XOR operations on integers ]]> &example.outputs; Bitwise XOR operations on strings ]]> Bit shifting on integers > $places; p($res, $val, '>>', $places, 'copy of sign bit shifted into left side'); $val = 4; $places = 2; $res = $val >> $places; p($res, $val, '>>', $places); $val = 4; $places = 3; $res = $val >> $places; p($res, $val, '>>', $places, 'bits shift out right side'); $val = 4; $places = 4; $res = $val >> $places; p($res, $val, '>>', $places, 'same result as above; can not shift beyond 0'); echo "\n--- BIT SHIFT RIGHT ON NEGATIVE INTEGERS ---\n"; $val = -4; $places = 1; $res = $val >> $places; p($res, $val, '>>', $places, 'copy of sign bit shifted into left side'); $val = -4; $places = 2; $res = $val >> $places; p($res, $val, '>>', $places, 'bits shift out right side'); $val = -4; $places = 3; $res = $val >> $places; p($res, $val, '>>', $places, 'same result as above; can not shift beyond -1'); echo "\n--- BIT SHIFT LEFT ON POSITIVE INTEGERS ---\n"; $val = 4; $places = 1; $res = $val << $places; p($res, $val, '<<', $places, 'zeros fill in right side'); $val = 4; $places = (PHP_INT_SIZE * 8) - 4; $res = $val << $places; p($res, $val, '<<', $places); $val = 4; $places = (PHP_INT_SIZE * 8) - 3; $res = $val << $places; p($res, $val, '<<', $places, 'sign bits get shifted out'); $val = 4; $places = (PHP_INT_SIZE * 8) - 2; $res = $val << $places; p($res, $val, '<<', $places, 'bits shift out left side'); echo "\n--- BIT SHIFT LEFT ON NEGATIVE INTEGERS ---\n"; $val = -4; $places = 1; $res = $val << $places; p($res, $val, '<<', $places, 'zeros fill in right side'); $val = -4; $places = (PHP_INT_SIZE * 8) - 3; $res = $val << $places; p($res, $val, '<<', $places); $val = -4; $places = (PHP_INT_SIZE * 8) - 2; $res = $val << $places; p($res, $val, '<<', $places, 'bits shift out left side, including sign bit'); /* * Ignore this bottom section, * it is just formatting to make output clearer. */ function p($res, $val, $op, $places, $note = '') { $format = '%0' . (PHP_INT_SIZE * 8) . "b\n"; printf("Expression: %d = %d %s %d\n", $res, $val, $op, $places); echo " Decimal:\n"; printf(" val=%d\n", $val); printf(" res=%d\n", $res); echo " Binary:\n"; printf(' val=' . $format, $val); printf(' res=' . $format, $res); if ($note) { echo " NOTE: $note\n"; } echo "\n"; } ?> ]]> &example.outputs.32bit; > 1 Decimal: val=4 res=2 Binary: val=00000000000000000000000000000100 res=00000000000000000000000000000010 NOTE: copy of sign bit shifted into left side Expression: 1 = 4 >> 2 Decimal: val=4 res=1 Binary: val=00000000000000000000000000000100 res=00000000000000000000000000000001 Expression: 0 = 4 >> 3 Decimal: val=4 res=0 Binary: val=00000000000000000000000000000100 res=00000000000000000000000000000000 NOTE: bits shift out right side Expression: 0 = 4 >> 4 Decimal: val=4 res=0 Binary: val=00000000000000000000000000000100 res=00000000000000000000000000000000 NOTE: same result as above; can not shift beyond 0 --- BIT SHIFT RIGHT ON NEGATIVE INTEGERS --- Expression: -2 = -4 >> 1 Decimal: val=-4 res=-2 Binary: val=11111111111111111111111111111100 res=11111111111111111111111111111110 NOTE: copy of sign bit shifted into left side Expression: -1 = -4 >> 2 Decimal: val=-4 res=-1 Binary: val=11111111111111111111111111111100 res=11111111111111111111111111111111 NOTE: bits shift out right side Expression: -1 = -4 >> 3 Decimal: val=-4 res=-1 Binary: val=11111111111111111111111111111100 res=11111111111111111111111111111111 NOTE: same result as above; can not shift beyond -1 --- BIT SHIFT LEFT ON POSITIVE INTEGERS --- Expression: 8 = 4 << 1 Decimal: val=4 res=8 Binary: val=00000000000000000000000000000100 res=00000000000000000000000000001000 NOTE: zeros fill in right side Expression: 1073741824 = 4 << 28 Decimal: val=4 res=1073741824 Binary: val=00000000000000000000000000000100 res=01000000000000000000000000000000 Expression: -2147483648 = 4 << 29 Decimal: val=4 res=-2147483648 Binary: val=00000000000000000000000000000100 res=10000000000000000000000000000000 NOTE: sign bits get shifted out Expression: 0 = 4 << 30 Decimal: val=4 res=0 Binary: val=00000000000000000000000000000100 res=00000000000000000000000000000000 NOTE: bits shift out left side --- BIT SHIFT LEFT ON NEGATIVE INTEGERS --- Expression: -8 = -4 << 1 Decimal: val=-4 res=-8 Binary: val=11111111111111111111111111111100 res=11111111111111111111111111111000 NOTE: zeros fill in right side Expression: -2147483648 = -4 << 29 Decimal: val=-4 res=-2147483648 Binary: val=11111111111111111111111111111100 res=10000000000000000000000000000000 Expression: 0 = -4 << 30 Decimal: val=-4 res=0 Binary: val=11111111111111111111111111111100 res=00000000000000000000000000000000 NOTE: bits shift out left side, including sign bit ]]> &example.outputs.64bit; > 1 Decimal: val=4 res=2 Binary: val=0000000000000000000000000000000000000000000000000000000000000100 res=0000000000000000000000000000000000000000000000000000000000000010 NOTE: copy of sign bit shifted into left side Expression: 1 = 4 >> 2 Decimal: val=4 res=1 Binary: val=0000000000000000000000000000000000000000000000000000000000000100 res=0000000000000000000000000000000000000000000000000000000000000001 Expression: 0 = 4 >> 3 Decimal: val=4 res=0 Binary: val=0000000000000000000000000000000000000000000000000000000000000100 res=0000000000000000000000000000000000000000000000000000000000000000 NOTE: bits shift out right side Expression: 0 = 4 >> 4 Decimal: val=4 res=0 Binary: val=0000000000000000000000000000000000000000000000000000000000000100 res=0000000000000000000000000000000000000000000000000000000000000000 NOTE: same result as above; can not shift beyond 0 --- BIT SHIFT RIGHT ON NEGATIVE INTEGERS --- Expression: -2 = -4 >> 1 Decimal: val=-4 res=-2 Binary: val=1111111111111111111111111111111111111111111111111111111111111100 res=1111111111111111111111111111111111111111111111111111111111111110 NOTE: copy of sign bit shifted into left side Expression: -1 = -4 >> 2 Decimal: val=-4 res=-1 Binary: val=1111111111111111111111111111111111111111111111111111111111111100 res=1111111111111111111111111111111111111111111111111111111111111111 NOTE: bits shift out right side Expression: -1 = -4 >> 3 Decimal: val=-4 res=-1 Binary: val=1111111111111111111111111111111111111111111111111111111111111100 res=1111111111111111111111111111111111111111111111111111111111111111 NOTE: same result as above; can not shift beyond -1 --- BIT SHIFT LEFT ON POSITIVE INTEGERS --- Expression: 8 = 4 << 1 Decimal: val=4 res=8 Binary: val=0000000000000000000000000000000000000000000000000000000000000100 res=0000000000000000000000000000000000000000000000000000000000001000 NOTE: zeros fill in right side Expression: 4611686018427387904 = 4 << 60 Decimal: val=4 res=4611686018427387904 Binary: val=0000000000000000000000000000000000000000000000000000000000000100 res=0100000000000000000000000000000000000000000000000000000000000000 Expression: -9223372036854775808 = 4 << 61 Decimal: val=4 res=-9223372036854775808 Binary: val=0000000000000000000000000000000000000000000000000000000000000100 res=1000000000000000000000000000000000000000000000000000000000000000 NOTE: sign bits get shifted out Expression: 0 = 4 << 62 Decimal: val=4 res=0 Binary: val=0000000000000000000000000000000000000000000000000000000000000100 res=0000000000000000000000000000000000000000000000000000000000000000 NOTE: bits shift out left side --- BIT SHIFT LEFT ON NEGATIVE INTEGERS --- Expression: -8 = -4 << 1 Decimal: val=-4 res=-8 Binary: val=1111111111111111111111111111111111111111111111111111111111111100 res=1111111111111111111111111111111111111111111111111111111111111000 NOTE: zeros fill in right side Expression: -9223372036854775808 = -4 << 61 Decimal: val=-4 res=-9223372036854775808 Binary: val=1111111111111111111111111111111111111111111111111111111111111100 res=1000000000000000000000000000000000000000000000000000000000000000 Expression: 0 = -4 << 62 Decimal: val=-4 res=0 Binary: val=1111111111111111111111111111111111111111111111111111111111111100 res=0000000000000000000000000000000000000000000000000000000000000000 NOTE: bits shift out left side, including sign bit ]]> Use functions from the gmp extension for bitwise manipulation on numbers beyond PHP_INT_MAX. &reftitle.seealso; pack unpack gmp_and gmp_or gmp_xor gmp_testbit gmp_clrbit
Comparison Operators Comparison operators, as their name implies, allow you to compare two values. You may also be interested in viewing the type comparison tables, as they show examples of various type related comparisons. Comparison Operators Example Name Result $a == $b Equal &true; if $a is equal to $b after type juggling. $a === $b Identical &true; if $a is equal to $b, and they are of the same type. $a != $b Not equal &true; if $a is not equal to $b after type juggling. $a <> $b Not equal &true; if $a is not equal to $b after type juggling. $a !== $b Not identical &true; if $a is not equal to $b, or they are not of the same type. $a < $b Less than &true; if $a is strictly less than $b. $a > $b Greater than &true; if $a is strictly greater than $b. $a <= $b Less than or equal to &true; if $a is less than or equal to $b. $a >= $b Greater than or equal to &true; if $a is greater than or equal to $b. $a <=> $b Spaceship An int less than, equal to, or greater than zero when $a is less than, equal to, or greater than $b, respectively.
If both operands are numeric strings, or one operand is a number and the other one is a numeric string, then the comparison is done numerically. These rules also apply to the switch statement. The type conversion does not take place when the comparison is === or !== as this involves comparing the type as well as the value. Prior to PHP 8.0.0, if a string is compared to a number or a numeric string then the string was converted to a number before performing the comparison. This can lead to surprising results as can be seen with the following example: ]]> &example.outputs.7; &example.outputs.8; 1; // 0 echo 1 <=> 2; // -1 echo 2 <=> 1; // 1 // Floats echo 1.5 <=> 1.5; // 0 echo 1.5 <=> 2.5; // -1 echo 2.5 <=> 1.5; // 1 // Strings echo "a" <=> "a"; // 0 echo "a" <=> "b"; // -1 echo "b" <=> "a"; // 1 echo "a" <=> "aa"; // -1 echo "zz" <=> "aa"; // 1 // Arrays echo [] <=> []; // 0 echo [1, 2, 3] <=> [1, 2, 3]; // 0 echo [1, 2, 3] <=> []; // 1 echo [1, 2, 3] <=> [1, 2, 1]; // 1 echo [1, 2, 3] <=> [1, 2, 4]; // -1 // Objects $a = (object) ["a" => "b"]; $b = (object) ["a" => "b"]; echo $a <=> $b; // 0 $a = (object) ["a" => "b"]; $b = (object) ["a" => "c"]; echo $a <=> $b; // -1 $a = (object) ["a" => "c"]; $b = (object) ["a" => "b"]; echo $a <=> $b; // 1 // not only values are compared; keys must match $a = (object) ["a" => "b"]; $b = (object) ["b" => "b"]; echo $a <=> $b; // 1 ?> ]]> For various types, comparison is done according to the following table (in order). Comparison with Various Types Type of Operand 1 Type of Operand 2 Result null or string string Convert &null; to "", numerical or lexical comparison bool or null anything Convert both sides to bool, &false; < &true; object object Built-in classes can define its own comparison, different classes are uncomparable, same class see Object Comparison string, resource, int or float string, resource, int or float Translate strings and resources to numbers, usual math array array Array with fewer members is smaller, if key from operand 1 is not found in operand 2 then arrays are uncomparable, otherwise - compare value by value (see following example) object anything object is always greater array anything array is always greater
Boolean/null comparison ]]> Transcription of standard array comparison count($op2)) { return 1; // $op1 > $op2 } foreach ($op1 as $key => $val) { if (!array_key_exists($key, $op2)) { return null; // uncomparable } elseif ($val < $op2[$key]) { return -1; } elseif ($val > $op2[$key]) { return 1; } } return 0; // $op1 == $op2 } ?> ]]> Comparison of floating point numbers Because of the way floats are represented internally, you should not test two floats for equality. See the documentation for float for more information. &reftitle.seealso; strcasecmp strcmp Array operators Types Ternary Operator Another conditional operator is the "?:" (or ternary) operator. Assigning a default value ]]> The expression (expr1) ? (expr2) : (expr3) evaluates to expr2 if expr1 evaluates to &true;, and expr3 if expr1 evaluates to &false;. It is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to &true;, and expr3 otherwise. Please note that the ternary operator is an expression, and that it doesn't evaluate to a variable, but to the result of an expression. This is important to know if you want to return a variable by reference. The statement return $var == 42 ? $a : $b; in a return-by-reference function will therefore not work and a warning is issued. It is recommended to avoid "stacking" ternary expressions. PHP's behaviour when using more than one unparenthesized ternary operator within a single expression is non-obvious compared to other languages. Indeed prior to PHP 8.0.0, ternary expressions were evaluated left-associative, instead of right-associative like most other programming languages. Relying on left-associativity is deprecated as of PHP 7.4.0. As of PHP 8.0.0, the ternary operator is non-associative. Non-obvious Ternary Behaviour ]]> Null Coalescing Operator Further exists the "??" (or null coalescing) operator. Assigning a default value ]]> The expression (expr1) ?? (expr2) evaluates to expr2 if expr1 is &null;, and expr1 otherwise. In particular, this operator does not emit a notice or warning if the left-hand side value does not exist, just like isset. This is especially useful on array keys. Please note that the null coalescing operator is an expression, and that it doesn't evaluate to a variable, but to the result of an expression. This is important to know if you want to return a variable by reference. The statement return $foo ?? $bar; in a return-by-reference function will therefore not work and a warning is issued. Please note that the null coalescing operator allows for simple nesting: Nesting null coalescing operator ]]>
Error Control Operators PHP supports one error control operator: the at sign (@). When prepended to an expression in PHP, any diagnostic error that might be generated by that expression will be suppressed. If a custom error handler function is set with set_error_handler, it will still be called even though the diagnostic has been suppressed, as such the custom error handler should call error_reporting and verify that the @ operator was used in the following way: ]]> Prior to PHP 8.0.0, the value of the severity passed to the custom error handler was always 0 if the diagnostic was suppressed. This is no longer the case as of PHP 8.0.0. Any error message generated by the expression is available in the "message" element of the array returned by error_get_last. The result of that function will change on each error, so it needs to be checked early. ]]> The @-operator works only on expressions. A simple rule of thumb is: if one can take the value of something, then one can prepend the @ operator to it. For instance, it can be prepended to variables, functions calls, certain language construct calls (e.g. include), and so forth. It cannot be prepended to function or class definitions, or conditional structures such as if and &foreach;, and so forth. Prior to PHP 8.0.0, it was possible for the @ operator to disable critical errors that will terminate script execution. For example, prepending @ to a call of a function which did not exist, by being unavailable or mistyped, would cause the script to terminate with no indication as to why. &reftitle.seealso; error_reporting Error Handling and Logging functions Execution Operators PHP supports one execution operator: backticks (``). Note that these are not single-quotes! PHP will attempt to execute the contents of the backticks as a shell command; the output will be returned (i.e., it won't simply be dumped to output; it can be assigned to a variable). Use of the backtick operator is identical to shell_exec. $output"; ?> ]]> The backtick operator is disabled when shell_exec is disabled. Unlike some other languages, backticks have no special meaning within double-quoted strings. &reftitle.seealso; Program Execution functions popen proc_open Using PHP from the commandline Incrementing/Decrementing Operators PHP supports C-style pre- and post-increment and decrement operators. The increment/decrement operators only affect numbers and strings. Arrays, objects, booleans and resources are not affected. Decrementing &null; values has no effect too, but incrementing them results in 1. Increment/decrement Operators Example Name Effect ++$a Pre-increment Increments $a by one, then returns $a. $a++ Post-increment Returns $a, then increments $a by one. --$a Pre-decrement Decrements $a by one, then returns $a. $a-- Post-decrement Returns $a, then decrements $a by one.
Here's a simple example script: Postincrement"; $a = 5; echo "Should be 5: " . $a++ . "
\n"; echo "Should be 6: " . $a . "
\n"; echo "

Preincrement

"; $a = 5; echo "Should be 6: " . ++$a . "
\n"; echo "Should be 6: " . $a . "
\n"; echo "

Postdecrement

"; $a = 5; echo "Should be 5: " . $a-- . "
\n"; echo "Should be 4: " . $a . "
\n"; echo "

Predecrement

"; $a = 5; echo "Should be 4: " . --$a . "
\n"; echo "Should be 4: " . $a . "
\n"; ?> ]]>
PHP follows Perl's convention when dealing with arithmetic operations on character variables and not C's. For example, in PHP and Perl $a = 'Z'; $a++; turns $a into 'AA', while in C a = 'Z'; a++; turns a into '[' (ASCII value of 'Z' is 90, ASCII value of '[' is 91). Note that character variables can be incremented but not decremented and even so only plain ASCII alphabets and digits (a-z, A-Z and 0-9) are supported. Incrementing/decrementing other character variables has no effect, the original string is unchanged. Arithmetic Operations on Character Variables ]]> &example.outputs; Incrementing or decrementing booleans has no effect.
Logical Operators Logical Operators Example Name Result $a and $b And &true; if both $a and $b are &true;. $a or $b Or &true; if either $a or $b is &true;. $a xor $b Xor &true; if either $a or $b is &true;, but not both. ! $a Not &true; if $a is not &true;. $a && $b And &true; if both $a and $b are &true;. $a || $b Or &true; if either $a or $b is &true;.
The reason for the two different variations of "and" and "or" operators is that they operate at different precedences. (See Operator Precedence.) Logical operators illustrated ]]> &example.outputs.similar;
String Operators There are two string operators. The first is the concatenation operator ('.'), which returns the concatenation of its right and left arguments. The second is the concatenating assignment operator ('.='), which appends the argument on the right side to the argument on the left side. Please read Assignment Operators for more information. ]]> &reftitle.seealso; String type String functions Array Operators Array Operators Example Name Result $a + $b Union Union of $a and $b. $a == $b Equality &true; if $a and $b have the same key/value pairs. $a === $b Identity &true; if $a and $b have the same key/value pairs in the same order and of the same types. $a != $b Inequality &true; if $a is not equal to $b. $a <> $b Inequality &true; if $a is not equal to $b. $a !== $b Non-identity &true; if $a is not identical to $b.
The + operator returns the right-hand array appended to the left-hand array; for keys that exist in both arrays, the elements from the left-hand array will be used, and the matching elements from the right-hand array will be ignored. "apple", "b" => "banana"); $b = array("a" => "pear", "b" => "strawberry", "c" => "cherry"); $c = $a + $b; // Union of $a and $b echo "Union of \$a and \$b: \n"; var_dump($c); $c = $b + $a; // Union of $b and $a echo "Union of \$b and \$a: \n"; var_dump($c); $a += $b; // Union of $a += $b is $a and $b echo "Union of \$a += \$b: \n"; var_dump($a); ?> ]]> When executed, this script will print the following: string(5) "apple" ["b"]=> string(6) "banana" ["c"]=> string(6) "cherry" } Union of $b and $a: array(3) { ["a"]=> string(4) "pear" ["b"]=> string(10) "strawberry" ["c"]=> string(6) "cherry" } Union of $a += $b: array(3) { ["a"]=> string(5) "apple" ["b"]=> string(6) "banana" ["c"]=> string(6) "cherry" } ]]> Elements of arrays are equal for the comparison if they have the same key and value. Comparing arrays "banana", "0" => "apple"); var_dump($a == $b); // bool(true) var_dump($a === $b); // bool(false) ?> ]]> &reftitle.seealso; Array type Array functions
Type Operators instanceof is used to determine whether a PHP variable is an instantiated object of a certain class: Using <literal>instanceof</literal> with classes ]]> &example.outputs; instanceof can also be used to determine whether a variable is an instantiated object of a class that inherits from a parent class: Using <literal>instanceof</literal> with inherited classes ]]> &example.outputs; To check if an object is not an instanceof a class, the logical not operator can be used. Using <literal>instanceof</literal> to check if object is <emphasis>not</emphasis> an instanceof a class ]]> &example.outputs; Lastly, instanceof can also be used to determine whether a variable is an instantiated object of a class that implements an interface: Using <literal>instanceof</literal> with interfaces ]]> &example.outputs; Although instanceof is usually used with a literal classname, it can also be used with another object or a string variable: Using <literal>instanceof</literal> with other variables ]]> &example.outputs; instanceof does not throw any error if the variable being tested is not an object, it simply returns &false;. Constants, however, were not allowed prior to PHP 7.3.0. Using <literal>instanceof</literal> to test other variables ]]> &example.outputs; As of PHP 7.3.0, constants are allowed on the left-hand-side of the instanceof operator. Using <literal>instanceof</literal> to test constants ]]> &example.outputs.73; The instanceof operator has a functional variant with the is_a function. &reftitle.seealso; get_class is_a