0
0
PHPprogramming~5 mins

Operator precedence and evaluation in PHP

Choose your learning style9 modes available
Introduction
Operator precedence tells us which part of a math or logic expression gets done first. It helps avoid confusion and makes sure the computer calculates things the way we expect.
When you write math formulas in your code and want to know which operations happen first.
When combining different types of operations like addition and multiplication in one line.
When using logical conditions with AND, OR, and NOT to control program flow.
When you want to make your code clearer by adding parentheses to change the order of calculation.
When debugging unexpected results in calculations or conditions.
Syntax
PHP
<?php
// Example of operator precedence
$result = 3 + 4 * 2;
echo $result; // Outputs 11
?>
Multiplication (*) has higher precedence than addition (+), so it happens first.
Use parentheses () to change the order and make your code easier to read.
Examples
Multiplication happens first: 3 * 4 = 12, then 2 + 12 = 14.
PHP
<?php
// Multiplication before addition
echo 2 + 3 * 4; // Outputs 14
?>
Parentheses make addition happen first: 2 + 3 = 5, then 5 * 4 = 20.
PHP
<?php
// Using parentheses to change order
echo (2 + 3) * 4; // Outputs 20
?>
AND (&&) happens before OR (||), so false && false = false, then true || false = true.
PHP
<?php
// Logical operators precedence
var_dump(true || false && false); // Outputs bool(true)
?>
Sample Program
This program shows how PHP calculates expressions based on operator precedence rules.
PHP
<?php
// Demonstrate operator precedence and evaluation
$a = 5 + 3 * 2; // 3*2=6, then 5+6=11
$b = (5 + 3) * 2; // 5+3=8, then 8*2=16
$c = true || false && false; // false && false = false, then true || false = true

echo "$a = $a\n";
echo "$b = $b\n";
echo "$c = ";
var_dump($c);
?>
OutputSuccess
Important Notes
Remember that multiplication and division happen before addition and subtraction.
Logical AND (&&) has higher precedence than logical OR (||).
Use parentheses to make your code clear and avoid mistakes.
Summary
Operator precedence decides which part of an expression runs first.
Multiplication and division come before addition and subtraction.
Parentheses can change the order and make your code easier to understand.