PHP Operators
# Chapter 5: PHP Operators
1. Introduction
Welcome to Chapter 5! Now that we have variables holding our data, we need ways to manipulate that data. This is where operators come in. Operators are special symbols that perform operations on variables and values. Whether you want to add two numbers, compare if passwords match, or combine two strings, operators are the tools you need. In this chapter, we will cover Arithmetic, Assignment, Comparison, Logical, and String operators.2. Learning Objectives
By the end of this chapter, you will be able to:- Perform mathematical calculations using Arithmetic Operators.
- Update variable values efficiently using Assignment Operators.
- Compare values using Comparison Operators.
- Chain conditions together using Logical Operators.
- Combine text using String Operators.
3. Arithmetic Operators
Arithmetic operators are used to perform common mathematical operations, such as addition, subtraction, multiplication, and division.-
+(Addition):$x + $y
-
-(Subtraction):$x - $y
-
*(Multiplication):$x * $y
-
/(Division):$x / $y
-
%(Modulus/Remainder):$x % $y
-
(Exponentiation):$x $y(x to the power of y)
4. Assignment Operators
Assignment operators are used to write a value to a variable. The most basic one is=. However, PHP has shorthand assignment operators to update existing variables.
-
=(Assign):$x = 5
-
+=(Add and assign):$x += 5(Same as$x = $x + 5)
-
-=(Subtract and assign):$x -= 5
-
*=(Multiply and assign):$x *= 5
5. Comparison Operators
Comparison operators compare two values and return a Boolean (true or false). These are vital for conditional statements.
-
==(Equal): Returns true if values are equal.
-
===(Identical): Returns true if values are equal AND of the same data type.
-
!=(Not equal): Returns true if values are not equal.
-
>(Greater than): Returns true if left is strictly greater than right.
-
<(Less than): Returns true if left is strictly less than right.
-
>=(Greater than or equal to)
-
<=(Less than or equal to)
6. Logical Operators
Logical operators are used to combine multiple conditional statements.-
&&orand(And): True if BOTH conditions are true.
-
||oror(Or): True if AT LEAST ONE condition is true.
-
!(Not): Reverses the boolean value. True becomes false, false becomes true.
7. String Operators
There are two specific operators for strings. They are used to concatenate (join together) strings.-
.(Concatenation): Joins two strings together.
-
.=(Concatenation assignment): Appends a string to an existing string variable.
8. Real-World Examples
Imagine an e-commerce cart. You need to calculate the total price, apply a discount, and check if the user qualifies for free shipping.9. Output Explanations
In the cart example,$itemprice * $quantity results in 76.5.
$total += $shippingcost adds 5, making $total 81.5.
Because 76.5 is greater than 50, $qualifiesforfreeshipping becomes true.
The final echo concatenates the text and the number, resulting in: Your total is $81.5.
10. Common Mistakes
-
Confusing
=and==: Using$x = 5inside a comparison instead of$x == 5. A single=*assigns* the value, it does not compare it!
-
Ignoring Data Types in Comparisons: Using
==when verifying critical data (like passwords or strict ID checks). Always prefer===to avoid unexpected type juggling bugs.
-
Forgetting spaces in string concatenation:
$first.$lastmight outputJohnDoewithout a space. You must explicitly add" ".
11. Best Practices
-
Always use the identical operator
===instead of==to prevent hidden bugs caused by PHP automatically changing data types during comparison.
-
Use parentheses
()to group complex logical operations to make the evaluation order clear. Example:if ( ($a && $b) || $c ).
12. Exercises
- 1. Use arithmetic operators to calculate the area of a rectangle (length * width) and echo the result.
-
2.
Create a variable and use the
.=operator to build a paragraph of text from three separate sentences.
-
3.
Compare the integer
10and the string"10"using both==and===andvardump()the results.
13. Mini Project: Simple Calculator Backend
Task: Build a script that mimics a calculator. Define two number variables and output their addition, subtraction, multiplication, and division in a neatly formatted HTML list.14. Coding Challenges
Challenge 1: You are building an ATM script. Define a variable$balance as 100 and $withdrawamount as 40. Write a logical comparison that returns true ONLY IF the $withdrawamount is less than or equal to the balance AND the $withdraw_amount is greater than 0.
15. MCQs with Answers
1. What does the% operator do?
A) Calculates percentages
B) Divides two numbers
C) Returns the remainder of a division
D) Multiplies two strings
*Answer: C*
2. Which operator checks if two values are equal AND of the exact same data type?
A) =
B) ==
C) ===
D) !==
*Answer: C*
3. What will be the value of $x after this code runs? $x = 10; $x += 5;
A) 5
B) 10
C) 15
D) Error
*Answer: C*
16. Interview Questions
Q: Explain the difference between== and ===.
*A:* The == operator is the equality operator. It checks if the values are the same, performing type coercion if necessary (e.g., 5 == "5" is true). The === operator is the identical operator. It checks if both the values AND the data types are exactly the same without any coercion (e.g., 5 === "5" is false).
Q: What is the concatenation operator in PHP?
*A:* In PHP, the dot . is used to concatenate (join) strings. This is different from many other languages (like JavaScript or Python) which use the + sign for string concatenation.
17. FAQs
Q: Can I use+ to join strings in PHP?
*A:* No. If you try to use + to join strings in PHP, it will attempt to convert those strings into numbers and perform mathematical addition, leading to errors or unexpected results. Always use the . dot operator for strings.