 PHP Part 3: Operators and Expressions in PHP

# PHP PART 3: OPERATORS AND EXPRESSIONS IN PHP

## Operators and Expressions in PHP

In this article, we’ll cover the most commonly used operators and expressions in PHP, along with their syntax, examples, and outputs.

Operators and expressions are fundamental components of any programming language, and PHP is no exception. Operators are symbols used to perform specific operations on values or variables, while expressions are combinations of values, variables, and operators that produce a result. In PHP, operators are arithmetic, comparison and logical. Let’s take a closer look at each type and how they work.

## Arithmetic Operators

Arithmetic operators are used to perform basic mathematical operations such as addition, subtraction, multiplication, division, and modulus. Here is an example of how these operators work in PHP:

``````<?php
\$a = 10;
\$b = 5;

echo \$a + \$b; // Output: 15

// Subtraction
echo \$a - \$b; // Output: 5

// Multiplication
echo \$a * \$b; // Output: 50

// Division
echo \$a / \$b; // Output: 2

// Modulus
echo \$a % \$b; // Output: 0
?>``````
```15
5
50
2
0
```

## Comparison Operators

Comparison operators are used to compare two values or variables. They return a boolean value, either true or false, based on the comparison. Here is an example of how these operators work in PHP:

``````<?php
\$a = 10;
\$b = 5;

// Equal to
echo \$a == \$b; // Output: 0

// Not equal to
echo \$a != \$b; // Output: 1

// Greater than
echo \$a > \$b; // Output: 1

// Less than
echo \$a < \$b; // Output: 0

// Greater than or equal to
echo \$a >= \$b; // Output: 1

// Less than or equal to
echo \$a <= \$b; // Output: 0
?>
``````

```0
1
1
0
1
0
```

## Logical Operators

Logical operators are used to combine two or more conditions to form a single, more complex condition. They return a boolean value based on the result of the combined conditions. Here is an example of how these operators work in PHP:

``````<?php
\$a = 10;
\$b = 5;
\$c = 3;

// And operator
if (\$a > \$b && \$a > \$c) {
echo "A is the largest number.";
} // Output: A is the largest number.

// Or operator
if (\$a == \$b || \$a == \$c) {
echo "A is equal to either B or C.";
} // Output: A is equal to either B or C.

// Not operator
if (!(\$a == \$b)) {
echo "A is not equal to B.";
} // Output: A is not equal to B.
?>
``````

### Output

```A is the largest number.
A is equal to either B or C.
A is not equal to B.
```

## Conclusion

In this article, we’ve covered the main operators and expressions in PHP, which are fundamental building blocks of any program. We started by introducing arithmetic operators, which allow us to perform basic calculations with numeric values. We then moved on to comparison operators, which enable us to compare values and evaluate conditions. Finally, we saw logical operators, which let us combine conditions and control the flow of a program.