Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

The - operator in PHP functions as both a binary arithmetic subtraction operator and a unary arithmetic negation operator, depending on its arity. It evaluates numeric expressions and applies PHP’s standard type juggling rules to non-numeric operands.

Binary Subtraction

When used with two operands, - calculates the difference by subtracting the right operand from the left operand.
$result = $expression1 - $expression2;
Return Type Resolution:
  • Returns an int if both operands evaluate to integers and the resulting value does not exceed the bounds of PHP_INT_MAX or PHP_INT_MIN.
  • Returns a float if either operand is a float, or if the subtraction results in an integer overflow or underflow.

Unary Negation

When used with a single operand, - inverts the algebraic sign of the value. Positive values become negative, and negative values become positive.
$result = -$expression;

Type Coercion and Strictness

PHP dynamically coerces scalar types during the evaluation of the - operator. In modern PHP (8.0+), strict type validation applies to non-numeric values:
  • Numeric Strings: Automatically cast to int or float based on the string’s format.
  • Booleans: true is cast to 1; false is cast to 0.
  • Null: Silently evaluates to 0.
  • Non-Numeric Strings: Throws a TypeError.
  • Arrays and Objects: Throws a TypeError.
// Type coercion mechanics
$a = "10" - 2;      // int(8)
$b = 5 - true;      // int(4)
$c = -false;        // int(0)
$d = 10 - null;     // int(10)

// PHP 8.0+ Error states
$e = 5 - "string";  // TypeError
$f = -[1, 2];       // TypeError

Precedence and Associativity

The PHP parser handles the - operator differently based on its context:
  • Unary -: Shares the exact same precedence level as increment (++), decrement (--), and type casting operators. Unary - is right-associative, meaning chained unary operators evaluate strictly from right to left.
  • Binary -: Shares precedence with addition (+). As of PHP 8.0, it has strictly higher precedence than string concatenation (.). Binary - is left-associative, meaning chained expressions are evaluated strictly from left to right.
// Left-associativity of binary subtraction
$val1 = 10 - 5 - 2; 
// Evaluates as: (10 - 5) - 2 = 3

// Right-associativity of unary negation
$val2 = - -5;
// Evaluates as: -(-5) = 5

// Precedence of unary negation vs binary arithmetic
$val3 = -5 + 3;
// Evaluates as: (-5) + 3 = -2
Master PHP with Deep Grasping Methodology!Learn More