Autocodewizard Logo Operators and Expressions - Autocodewizard Ebooks - PHP Essentials: Building Dynamic Web Applications

Chapter 3: Operators and Expressions

Explore PHP operators and expressions, including arithmetic, comparison, and logical operators, to perform dynamic calculations and comparisons.

In this chapter, we’ll cover PHP operators and expressions. Operators are symbols that represent operations applied to values, enabling you to perform calculations, comparisons, and logical tests. Understanding these operators will allow you to create more dynamic and interactive code.

Arithmetic Operators

PHP supports standard arithmetic operators, which you can use to perform calculations:

<?php
$a = 10;
$b = 3;
echo $a + $b;  // Outputs: 13
echo $a % $b;  // Outputs: 1 (remainder of 10 / 3)
?>

Comparison Operators

Comparison operators are used to compare values. They return true or false depending on the result:

<?php
$x = 5;
$y = "5";
echo $x == $y;   // Outputs: 1 (true)
echo $x === $y;  // Outputs:  (false)
?>

In this example, $x == $y returns true because the values are equal, but $x === $y returns false because they are not of the same type.

Logical Operators

Logical operators allow you to combine multiple conditions. They return true or false based on the result of the combined conditions:

<?php
$isAdmin = true;
$isLoggedIn = true;

if ($isAdmin && $isLoggedIn) {
    echo "Welcome, Admin!";
} else {
    echo "Access denied.";
}
?>

In this example, the message "Welcome, Admin!" is displayed if both $isAdmin and $isLoggedIn are true.

Assignment Operators

Assignment operators are used to assign values to variables. The most common one is =, but there are other compound assignment operators:

<?php
$num = 10;
$num += 5; // Equivalent to $num = $num + 5
echo $num; // Outputs: 15
?>

Combining Operators in Expressions

Operators can be combined in expressions to perform complex calculations and comparisons:

<?php
$score = 75;
$grade = ($score >= 90) ? "A" : (($score >= 80) ? "B" : "C");
echo "Grade: " . $grade; // Outputs: Grade: C
?>

In this example, a ternary operator is used to determine the grade based on the score.

Summary and Next Steps

In this chapter, we covered PHP operators, including arithmetic, comparison, logical, and assignment operators. With these operators, you can create expressions to manipulate data, make comparisons, and control the flow of your PHP code. In the next chapter, we’ll explore conditional statements to further control the logic of your PHP applications.