PHP Expressions

Almost everything in a PHP script is an expression. Anything that has a value is an expression. In a typical assignment statement ($x=100), a literal value, a function or operands processed by operators is an expression − anything that appears to the right of assignment operator (=).

Syntax

$x = 100;           // 100 is an expression
$a = $b + $c;       // $b + $c is an expression
$c = add($a, $b);   // add($a, $b) is an expression
$val = sqrt(100);   // sqrt(100) is an expression
$var = $x != $y;    // $x != $y is an expression

Expression with Increment and Decrement Operators

These operators are called increment (++) and decrement (--) operators respectively. They are unary operators, needing just one operand and can be used in prefix or postfix manner, although with different effect on value of expression.

Both prefix and postfix ++ operators increment value of operand by 1 (whereas -- operator decrements by 1). However, when used in assignment expression, prefix makes increment/decrement first and then followed by assignment. In case of postfix, assignment is done before increment/decrement.

Postfix Increment Example

<?php
$x = 10;
$y = $x++;  // equivalent to $y = $x followed by $x = $x + 1
echo "x = $x y = $y";
?>
x = 11 y = 10

Prefix Increment Example

<?php
$x = 10;
$y = ++$x;  // equivalent to $x = $x + 1 followed by $y = $x
echo "x = $x y = $y";
?>
x = 11 y = 11

Expression with Ternary Conditional Operator

Ternary operator has three operands. First one is a logical expression. If it is TRUE, second operand expression is evaluated otherwise third one is evaluated ?

<?php
$marks = 60;
$result = $marks < 50 ? "fail" : "pass";
echo $result;
?>
pass

Conclusion

PHP expressions are fundamental building blocks that represent values in your code. Understanding how different operators affect expressions, especially increment/decrement and ternary operators, is crucial for writing effective PHP programs.

Updated on: 2026-03-15T09:17:02+05:30

12K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements