What Are We Doing in This Post?
In Episode 03, we learned how to store information in variables. But storing data is only half the job. The other half is doing something with it — calculating, comparing, combining, and manipulating.
That is what this episode is about.
We cover two things: operators and string functions. By the end, PHP will feel much more like a real tool and less like a collection of syntax rules.
Part 1 — Operators
An operator is a symbol that performs an action on one or more values.
You already know some operators from school. Plus sign adds numbers. Minus sign subtracts. PHP has those, and a few more that are specific to programming.
Arithmetic Operators — PHP as a Calculator
<?php
$a = 20; $b = 6;
echo $a + $b; echo "<br>";
echo $a - $b; echo "<br>";
echo $a * $b; echo "<br>";
echo $a / $b; echo "<br>";
echo $a % $b; echo "<br>";
echo $a ** 2;
?>
Output:
26 14 120 3.3333333333333 2 400
The percent sign is the modulus operator. It gives you the remainder after division. 20 divided by 6 is 3 with a remainder of 2. So 20 % 6 gives 2.
Real world use of modulus: checking if a number is even or odd. Any number modulus 2 gives either 0 (even) or 1 (odd). We will use this in Episode 05.
The double asterisk is the exponent operator. $a ** 2 means 20 to the power of 2, which is 400.
Assignment Operators — Shortcuts for Updating Variables
You already know the basic assignment operator: the equals sign stores a value into a variable.
PHP also has shortcut operators for updating a variable based on its current value.
<?php
$score = 100;
$score += 50; echo $score; echo "<br>";
$score -= 30; echo $score; echo "<br>";
$score *= 2; echo $score; echo "<br>";
$score /= 4; echo $score;
?>
Output:
150 120 240 60
$score += 50 means: take the current value of $score, add 50 to it, and store the result back into $score. It is a shortcut for writing $score = $score + 50.
Real world analogy: Think of your bank account balance. You do not open a new account every time money is added. You update the existing balance. That is exactly what these shortcut operators do.
Increment and Decrement Operators
These are used so often in PHP that they have their own dedicated symbols.
<?php
$counter = 0;
$counter++; echo $counter; echo "<br>";
$counter++; echo $counter; echo "<br>";
$counter--; echo $counter;
?>
Output:
1 2 1
$counter++ adds 1 to the variable. $counter-- subtracts 1. You will use these constantly when working with loops in Episode 06.
Comparison Operators — Asking PHP Questions
Comparison operators compare two values and return a boolean — either true or false.
<?php
$age = 20;
var_dump($age == 20); var_dump($age == 25); var_dump($age != 25); var_dump($age > 18); var_dump($age < 18); var_dump($age >= 20); var_dump($age <= 19);
?>
Output:
bool(true) bool(false) bool(true) bool(true) bool(false) bool(true) bool(false)
Notice the double equals sign for comparison. A single equals sign assigns a value. A double equals sign checks if two values are equal. Confusing these two is one of the most common beginner mistakes in PHP.
The triple equals sign — strict comparison:
<?php
$value = "20";
var_dump($value == 20); var_dump($value === 20);
?>
Output:
bool(true) bool(false)
Double equals checks value only. It sees "20" and 20 as equal because PHP converts the string to a number for comparison.
Triple equals checks value AND type. "20" is a string and 20 is an integer — different types, so it returns false.
Rule of thumb: use triple equals whenever you want to be precise. It prevents subtle bugs.
Logical Operators — Combining Conditions
Logical operators let you combine multiple comparisons.
<?php
$age = 25; $has_id = true;
var_dump($age >= 18 && $has_id == true);
var_dump($age < 18 || $has_id == true);
var_dump(!$has_id);
?>
Output:
bool(true) bool(true) bool(false)
&& means AND — both conditions must be true for the result to be true.
|| means OR — at least one condition must be true for the result to be true.
! means NOT — it flips the boolean. !true becomes false, !false becomes true.
Real world analogy: To enter a club, you must be over 18 AND have a valid ID. Both conditions required — that is AND. To get a discount, you can be a student OR a senior citizen. Either one works — that is OR.
Part 2 — String Functions
PHP comes with hundreds of built-in functions. Functions are ready-made tools — you call them by name, give them input, and they return a result.
String functions specifically work with text. Here are the most useful ones you will use constantly.
strlen — Count Characters in a String
<?php
$username = "Gagan"; echo strlen($username);
?>
Output: 5
strlen counts every character including spaces. Real world use: validating that a password is at least 8 characters long.
strtoupper and strtolower — Change Case
<?php
$name = "gagan sharma";
echo strtoupper($name); echo "<br>"; echo strtolower("HELLO WORLD");
?>
Output:
GAGAN SHARMA hello world
Real world use: storing emails in the database always in lowercase so that "Gagan@Gmail.com" and "gagan@gmail.com" are treated as the same email.
trim — Remove Extra Spaces
<?php
$input = " gagan "; echo strlen($input); echo "<br>";
$clean = trim($input); echo strlen($clean); echo "<br>"; echo $clean;
?>
Output:
11 5 gagan
trim removes whitespace from the beginning and end of a string. Users often accidentally type spaces before or after their input in forms. trim cleans that up before you store it in the database.
str_replace — Find and Replace Text
<?php
$message = "Hello World, World is beautiful."; $result = str_replace("World", "PHP", $message); echo $result;
?>
Output: Hello PHP, PHP is beautiful.
str_replace finds every occurrence of the first argument and replaces it with the second argument. Real world use: censoring bad words, replacing placeholders in email templates.
strpos — Find the Position of a Word
<?php
$email = "gagan@gmail.com"; $position = strpos($email, "@"); echo $position;
?>
Output: 5
strpos returns the position (index) of the first occurrence of a string. Positions start at 0 in PHP. So the @ symbol is at position 5 — meaning there are 5 characters before it.
If the string is not found, strpos returns false. Real world use: checking if an email contains @ before accepting it as valid.
substr — Extract Part of a String
<?php
$email = "gagan@gmail.com"; $domain = substr($email, 6); echo $domain;
?>
Output: gmail.com
substr cuts out a portion of a string. The second argument is the starting position. You can also pass a third argument for length.
<?php
$text = "Hello World"; echo substr($text, 0, 5);
?>
Output: Hello
Starting at position 0, extract 5 characters.
ucfirst and ucwords — Capitalize Text
<?php
$name = "gagan sharma";
echo ucfirst($name); echo "<br>"; echo ucwords($name);
?>
Output:
Gagan sharma Gagan Sharma
ucfirst capitalizes only the first character. ucwords capitalizes the first character of every word. Real world use: formatting user names before displaying them on a profile page.
A Real World Example — User Registration Cleanup
Let us combine everything we learned. Imagine a user submits a registration form. Before storing their data, we want to clean and format it properly.
<?php
$raw_name = " gagan sharma "; $raw_email = " Gagan@Gmail.COM "; $raw_password = "mypassword123";
$name = ucwords(trim($raw_name));
$email = strtolower(trim($raw_email));
$password_length = strlen($raw_password);
if ($password_length >= 8) { $password_valid = true; } else { $password_valid = false; }
echo "Name: $name"; echo "<br>"; echo "Email: $email"; echo "<br>"; echo "Password length: $password_length characters"; echo "<br>"; echo "Password valid: "; var_dump($password_valid);
?>
Output:
Name: Gagan Sharma Email: gagan@gmail.com Password length: 13 characters Password valid: bool(true)
This is exactly the kind of processing that happens on real registration pages. The user types messy input. PHP cleans it, formats it, validates it, and then it gets stored in the database.
What Did We Learn in This Post?
Arithmetic operators let PHP do math: addition, subtraction, multiplication, division, modulus, and exponent.
Assignment shortcut operators update a variable based on its current value without rewriting the full expression.
Comparison operators compare values and return true or false. Use triple equals for strict type-safe comparison.
Logical operators combine conditions: AND requires both conditions true, OR requires at least one true, NOT flips a boolean.
String functions are built-in tools for working with text: strlen counts characters, trim removes extra spaces, strtolower and strtoupper change case, str_replace swaps text, strpos finds position, substr extracts parts, and ucwords capitalizes words.
What is Coming in Episode 05?
Now that we know how to store data and work with it, we need to teach PHP how to make decisions.
Episode 05 covers conditionals — if, else, elseif, and switch. This is where PHP starts feeling like real logic. We will build a practical example: a grading system that takes a score and outputs a grade with a message.
See you in the next one.
Next Episode: Conditionals — Teaching PHP How to Make Decisions
This is Episode 04 of the PHP and Laravel — Zero to Hero series.
No comments:
Post a Comment