else if vs elseif in PHP — What's the Difference and Which Should You Use?

If you've been writing PHP for a while, you've probably used both else if (two words) and elseif (one word) without thinking much about it. They look almost identical, they behave almost identically, and PHP accepts both without complaint. So what's actually going on under the hood?

Let's break it down.


The Basics First

Here's the classic conditional structure most developers learn on day one:

$score = 75;

if ($score >= 90) {
    echo "Grade: A";
} elseif ($score >= 75) {
    echo "Grade: B";
} elseif ($score >= 60) {
    echo "Grade: C";
} else {
    echo "Grade: F";
}

Clean, readable, and works perfectly. Now swap every elseif with else if — it still works. So why does PHP have two ways to write the same thing?


They Are NOT Always the Same

Here's the critical part most tutorials skip.

With Curly Braces {} — Both Work Identically

if ($x > 10) {
    echo "big";
} else if ($x > 5) {
    echo "medium";
} else {
    echo "small";
}
if ($x > 10) {
    echo "big";
} elseif ($x > 5) {
    echo "medium";
} else {
    echo "small";
}

These two blocks compile to the same bytecode. Zero difference.

With Colon Syntax : — Only elseif is Valid

PHP supports an alternative syntax for control structures, commonly used inside HTML templates:

<?php if ($isLoggedIn): ?>
    <p>Welcome back!</p>
<?php elseif ($isGuest): ?>
    <p>Hello, guest!</p>
<?php else: ?>
    <p>Please log in.</p>
<?php endif; ?>

Now try using else if here:

<?php if ($isLoggedIn): ?>
    <p>Welcome back!</p>
<?php else if ($isGuest): ?>   <!-- Parse error! -->
    <p>Hello, guest!</p>
<?php endif; ?>

PHP throws a parse error. This is because else if in the colon syntax creates a nested if inside else, breaking the endif pairing. The parser no longer knows which if the endif closes.

This is the one real, concrete difference between the two.


What's Happening Internally

When you write else if (two words) with curly braces, PHP actually parses it as a nested structure:

// What you write
} else if ($condition) {

// What PHP actually sees
} else {
    if ($condition) {
    }
}

It's else followed by a new if block nested inside it. PHP is smart enough to flatten this in the compiled output when you're using curly braces, so performance is identical. But with colon syntax, that nesting breaks the template structure — which is why else if is forbidden there.

elseif (one word), on the other hand, is a dedicated keyword. PHP treats it as a single, flat continuation of the conditional chain — no hidden nesting involved.


Performance — Is There Any Difference?

Short answer: No.

With curly braces, both forms produce identical opcodes. PHP's compiler optimizes else if into the same flat structure as elseif. You will never notice a performance difference in any real application.


So Which One Should You Use?

Follow this simple rule:

Situation Use
Standard curly brace blocks Either works — pick one and be consistent
Alternative colon/template syntax Always use elseif
Team or framework codebase Follow the existing style guide

PSR-12 and Community Convention

The PHP-FIG's PSR-12 coding standard — the most widely adopted PHP style guide — explicitly recommends elseif over else if:

"The keyword elseif SHOULD be used instead of else if so that all control keywords look like single words."

Laravel, Symfony, and most major PHP frameworks follow PSR-12. If you're writing professional PHP, elseif is the right default.


Quick Reference

// Recommended — works everywhere
if ($a) {
    // ...
} elseif ($b) {
    // ...
} else {
    // ...
}

// Also valid — but only with curly braces
if ($a) {
    // ...
} else if ($b) {
    // ...
} else {
    // ...
}

// Template syntax — elseif ONLY, else if will throw a parse error
<?php if ($a): ?>
    ...
<?php elseif ($b): ?>
    ...
<?php else: ?>
    ...
<?php endif; ?>

The Bottom Line

elseif and else if are functionally identical in curly brace contexts, but elseif is the only valid option in PHP's alternative colon syntax. Beyond correctness, elseif is what PSR-12 recommends, what major frameworks enforce, and what makes your code look intentional and professional.

Pick elseif. Use it everywhere. Move on to harder problems.

Why PHP Doesn't Need a Closing ?> Tag — And Why That's Actually a Good Thing

If you've written PHP inside a .php file and noticed that omitting the closing ?> tag doesn't break anything, you're not imagining it. The file runs perfectly, output is correct, and PHP doesn't complain. VS Code might not even flag it as an issue.

So what's going on?


First, Understand What ?> Actually Does

The closing tag ?> is an instruction to the PHP parser — it says:

"Stop processing PHP here. Everything after this point is raw HTML/text — send it directly to the output buffer."

So in a mixed HTML + PHP file, it makes perfect sense:

<?php
$name = "Gagan";
?>
<h1>Hello, <?php echo $name; ?></h1>
<p>Welcome to my site.</p>

Here ?> is necessary because you're switching between PHP mode and HTML mode multiple times. The parser needs to know when to stop treating content as PHP code.


So Why Does a Pure PHP File Work Without It?

When your file contains only PHP — no HTML after the last line — the parser reaches the end of the file and simply stops. There is no HTML waiting to be sent, nothing to switch to. The closing tag's job was already done by the file ending.

PHP's parser behavior is:

"If I reach EOF while still in PHP mode, that's fine. I'll just stop here."

<?php

class UserService
{
    public function getUser(int $id): array
    {
        return ['id' => $id, 'name' => 'Gagan'];
    }
}

No ?> at the bottom. PHP reads the opening <?php, processes everything, hits EOF, and exits cleanly. Full success.


The Real Reason You Should OMIT ?>

This is where it gets interesting — and practical.

The Whitespace / Newline Problem

When you add ?> at the end of a file, PHP does something you might not expect. Any whitespace, newline, or blank line that exists after the closing tag gets sent to the output buffer as raw content.

<?php

function add(int $a, int $b): int
{
    return $a + $b;
}
?>

See that blank line after ?>? PHP sends that as output. A literal \n character is now part of your response — before any of your actual intended output.

Now imagine this file is included in a larger application:

<?php
// some-functions.php is included here
require_once 'some-functions.php';

header('Content-Type: application/json');
echo json_encode(['status' => 'ok']);

You'll get this error:

Warning: Cannot modify header information - headers already sent by
(output started at some-functions.php:9)

A single invisible newline broke your headers. This kind of bug is notoriously difficult to track down, especially in large codebases where files are required/included across many layers.

The fix? Never add ?> in the first place.


What PSR-12 Says

PHP-FIG's PSR-12 standard is explicit about this:

"A file SHOULD either declare symbols (classes, functions, constants, etc.) or cause side-effects (e.g. generate output, change .ini settings, etc.) but SHOULD NOT do both. The closing ?> tag MUST be omitted from files containing only PHP."

Laravel, Symfony, WordPress (modern code), and virtually every professional PHP codebase follow this rule. If you open any controller, model, or service class in Laravel, you will never see a closing ?>.


When IS ?> Required?

Only in one scenario — files that intentionally mix PHP and HTML, like template files:

<!DOCTYPE html>
<html>
<head>
    <title><?php echo $pageTitle; ?></title>
</head>
<body>
    <?php if ($isLoggedIn): ?>
        <p>Welcome, <?php echo $userName; ?></p>
    <?php else: ?>
        <p>Please log in.</p>
    <?php endif; ?>
</body>
</html>

Here, ?> is doing real work — it's toggling the parser between PHP mode and HTML output mode. You need it here. But notice — even this file doesn't need a closing ?> at the very end, because there's no PHP block left to close after the final HTML line.


Summary Table

File Type Closing ?>
Pure PHP class / service / controller Omit — always
Pure PHP config / constants file Omit — always
PHP + HTML mixed template Use it between blocks, omit at end
PHP file included via require / include Omit — headers risk

The Bottom Line

PHP was designed to be embedded inside HTML, which is why ?> exists at all. But when a file is pure PHP, the closing tag is not just unnecessary — it's a silent bug waiting to happen. An accidental newline after it can corrupt headers, break JSON responses, and ruin session handling.

VS Code removing it automatically (or not flagging its absence) isn't a quirk — it's the editor agreeing with PSR-12. Omit the closing tag in every pure PHP file, every time, without exception.

PHP & Laravel — Zero to Hero Episode 05: Conditionals — Teaching PHP How to Make Decisions

What Are We Doing in This Post?

So far PHP has been doing exactly what we tell it — store this, print that, calculate this. It has no brain of its own yet.

In this episode, we give PHP a brain.

Conditionals let PHP look at a situation and decide what to do based on the data. This is the foundation of all real programming logic. Every feature you have ever used on a website — login checks, permission systems, discount calculators, form validation — uses conditionals at its core.


The if Statement — The Most Basic Decision

Real world analogy: You check the weather before leaving home. If it is raining, you take an umbrella. That is an if statement in real life.

In PHP:

<?php

$is_raining = true;

if ($is_raining) { echo "Take an umbrella."; }

?>

Output: Take an umbrella.

The code inside the curly braces only runs if the condition inside the parentheses is true. If $is_raining were false, nothing would be printed at all.

The structure is always the same: the keyword if, then the condition in parentheses, then the code to run inside curly braces.


The else Statement — Handling the Other Case

What if you want to do something when the condition is false as well?

<?php

$is_raining = false;

if ($is_raining) { echo "Take an umbrella."; } else { echo "No umbrella needed. Enjoy the sun."; }

?>

Output: No umbrella needed. Enjoy the sun.

else runs when the if condition is false. You always get exactly one of the two outcomes — never both, never neither.


The elseif Statement — Handling Multiple Cases

Sometimes there are more than two possible situations.

Real world analogy: A traffic light. If it is green, go. If it is yellow, slow down. If it is red, stop.

<?php

$light = "yellow";

if ($light == "green") { echo "Go."; } elseif ($light == "yellow") { echo "Slow down."; } elseif ($light == "red") { echo "Stop."; } else { echo "Unknown signal. Proceed with caution."; }

?>

Output: Slow down.

PHP checks each condition from top to bottom. The moment it finds a true condition, it runs that block and skips everything else. The final else at the bottom is a safety net — it catches any case that none of the above conditions matched.

You can chain as many elseif blocks as you need.


Comparison Operators Inside Conditions

Now the comparison operators from Episode 04 become truly useful. Let us build a real example — an age-based access checker.

<?php

$age = 16;

if ($age >= 18) { echo "Access granted. Welcome."; } elseif ($age >= 13) { echo "Access granted for teens. Some content is restricted."; } else { echo "Access denied. You must be at least 13 years old."; }

?>

Output: Access granted for teens. Some content is restricted.

Change the value of $age and run it again. Try 10, 15, 20. Watch the output change. This is dynamic logic — the same code produces different results based on the data.


Logical Operators Inside Conditions

You can combine multiple conditions in a single if statement using the logical operators from Episode 04.

<?php

$age = 20; $has_ticket = true;

if ($age >= 18 && $has_ticket) { echo "Entry allowed."; } else { echo "Entry denied."; }

?>

Output: Entry allowed.

Both conditions must be true for entry to be allowed. Change $has_ticket to false and the output becomes Entry denied — even though the age condition is still true.

<?php

$is_member = false; $has_coupon = true;

if ($is_member || $has_coupon) { echo "Discount applied."; } else { echo "No discount available."; }

?>

Output: Discount applied.

Either condition being true is enough. The user has a coupon, so they get the discount even though they are not a member.


Nested if Statements — Decisions Inside Decisions

You can put an if statement inside another if statement. This is called nesting.

<?php

$is_logged_in = true; $is_admin = false;

if ($is_logged_in) { echo "Welcome back!"; echo "<br>";

if ($is_admin) {
    echo "You have admin access.";
} else {
    echo "You have standard user access.";
}

} else { echo "Please log in to continue."; }

?>

Output:

Welcome back! You have standard user access.

The outer if checks if the user is logged in at all. Only after confirming that does the inner if check their role. This mirrors exactly how login and permission systems work on real websites.


The switch Statement — Cleaner Multiple Choice

When you have one variable being compared against many specific values, elseif chains can get messy. The switch statement is cleaner for this situation.

<?php

$day = "Wednesday";

switch ($day) { case "Monday": echo "Start of the work week. Stay focused."; break; case "Wednesday": echo "Midweek. You are halfway there."; break; case "Friday": echo "Almost the weekend!"; break; case "Saturday": case "Sunday": echo "Weekend. Rest and recharge."; break; default: echo "Just another day. Keep going."; }

?>

Output: Midweek. You are halfway there.

switch takes the variable and checks it against each case from top to bottom. When it finds a match, it runs that block. The break keyword tells PHP to exit the switch after running the matched case. Without break, PHP would continue running every case below the match — almost always not what you want.

The default block at the bottom works like else — it runs when nothing else matched.

Notice Saturday and Sunday share the same output. You can stack cases on top of each other when they should produce the same result.


The Ternary Operator — Short if/else in One Line

When your condition is simple and you just want to assign one of two values, PHP gives you a shortcut called the ternary operator.

<?php

$age = 20; $status = ($age >= 18) ? "Adult" : "Minor"; echo $status;

?>

Output: Adult

The structure is: condition ? value if true : value if false

Read it as: "Is age greater than or equal to 18? If yes, use Adult. If no, use Minor."

Use ternary for simple one-line decisions. Use full if/else for anything more complex — readability matters.


The Null Coalescing Operator — Handling Missing Values

This one is specific to PHP and extremely useful when working with form data.

<?php

$username = null; $display_name = $username ?? "Guest"; echo $display_name;

?>

Output: Guest

The ?? operator checks if the left side is null or not set. If it is null, it uses the right side as the fallback value. If it is not null, it uses the left side.

Real world use: a user visits your page without logging in. Their username is null. You want to display "Guest" instead of nothing. This operator handles that in one clean line.


A Real World Example — Student Grade Calculator

Let us build a complete practical example combining everything from this episode.

Create a new file in your phplearning folder called grades.php and write this:

<!DOCTYPE html> <html> <head> <title>Grade Calculator</title> </head> <body>

<?php

$student_name = "Gagan"; $score = 78;

if ($score >= 90) { $grade = "A"; $message = "Outstanding performance!"; } elseif ($score >= 75) { $grade = "B"; $message = "Good work. Keep it up."; } elseif ($score >= 60) { $grade = "C"; $message = "Average performance. You can do better."; } elseif ($score >= 40) { $grade = "D"; $message = "Below average. More effort needed."; } else { $grade = "F"; $message = "Failed. Please review the material."; }

$result = ($score >= 40) ? "Pass" : "Fail";

echo "<h2>Result Card</h2>"; echo "<p>Student: $student_name</p>"; echo "<p>Score: $score / 100</p>"; echo "<p>Grade: $grade</p>"; echo "<p>Result: $result</p>"; echo "<p>Remark: $message</p>";

?>

</body> </html>

Visit http://localhost:8080/phplearning/grades.php

Try changing $score to different values — 95, 72, 55, 30 — and refresh the page each time. Watch every output change based on the score. This is exactly how a real school management system calculates and displays grades.


What Did We Learn in This Post?

if runs a block of code only when a condition is true.

else handles the case when the if condition is false.

elseif handles multiple conditions in sequence — PHP checks each one top to bottom and runs the first true one.

Logical operators AND and OR let you combine multiple conditions inside a single if statement.

Nested if statements let you put decisions inside decisions — essential for role and permission systems.

switch is cleaner than long elseif chains when comparing one variable against many specific values.

The ternary operator is a one-line shortcut for simple if/else assignments.

The null coalescing operator ?? provides a fallback value when a variable is null or not set.


What is Coming in Episode 06?

Now that PHP can make decisions, we need to teach it to repeat tasks.

Episode 06 covers loops — while, do while, for, and foreach. Loops are how PHP processes lists of data, generates repeated HTML, and handles large amounts of information without you writing the same code a hundred times.

See you in the next one.


Next Episode: Loops — Teaching PHP to Repeat Tasks Automatically

This is Episode 05 of the PHP and Laravel — Zero to Hero series.

PHP & Laravel — Zero to Hero Episode 04: Operators and String Functions — Making PHP Do the Work For You

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.

PHP & Laravel — Zero to Hero Episode 03: Variables and Data Types — How PHP Stores Information

What Are We Doing in This Post?

Your environment is ready. PHP is running. Now we start writing real code.

In this episode, we learn about variables and data types. These are the absolute foundation of any programming language. Every program you will ever write — no matter how complex — uses variables. Understanding them properly from the start makes everything else easier.


What is a Variable?

A variable is a container that stores information.

That is it. Nothing more complicated than that.

Real world analogy: Think of a variable like a labeled box. You have a box, you write a name on it, and you put something inside. Later, whenever you need that thing, you just look for the box with that label.

In PHP, every variable starts with a dollar sign followed by the name you choose.


    <?php

    $name = "Gagan";
    $age = 22;

    echo $name;
    echo $age;

    ?>

The dollar sign tells PHP: "this is a variable." The equals sign does not mean "equal to" in PHP — it means "store this value into this container." This is called assignment.

Run this in your browser. You will see: Gagan22

They appear together because echo just prints the value directly. We will fix the spacing in a moment.


PHP Variable Rules

Before we go further, learn these rules once. They will save you from confusing errors later.

Variable names must start with a dollar sign followed by a letter or underscore. They cannot start with a number.

$name — valid

$_price — valid

$1product — not valid, will cause an error

Variable names are case sensitive. $Name and $name are two completely different variables in PHP.

Variable names cannot have spaces. Use underscore or camelCase instead.

$first_name — valid

$firstName — valid

$first name — not valid


Data Types — What Kind of Information Can PHP Store?

Not all information is the same. A name is different from a number. A number is different from a true/false value. PHP handles different kinds of information using data types.

Here are the four most important ones for now.

1. String

A string is text. Any sequence of characters wrapped in quotes.


    <?php

    $name = "Gagan";
    $city = "Delhi";
    $message = "Welcome to my website!";

    echo $message;
    echo $name;
    echo $city;

    ?>

You can use double quotes or single quotes for strings. Both work. Double quotes have a special ability we will see shortly.

2. Integer

An integer is a whole number — no decimal point.


    <?php

    $age = 22;
    $year = 2025;
    $score = -10;

    echo $age;

No quotes around numbers. If you write $age = "22" with quotes, PHP treats it as a string, not a number. The difference matters when you do math.

3. Float

A float is a number with a decimal point.


    <?php

    $price = 99.99;
    $temperature = 36.6;
    $discount = 0.15;

    echo $price;

4. Boolean

A boolean stores only one of two values: true or false. Nothing else.


    <?php

    $is_logged_in = true;
    $has_paid = false;

    echo $is_logged_in;

When you echo a boolean, true prints as 1 and false prints as nothing. Booleans are not really meant to be printed — they are meant to be used in conditions. We will use them heavily starting Episode 05 when we cover if/else.


Seeing Your Variables Clearly — Using echo Properly

Earlier our output came out as Gagan22 with no space. Let us fix that and learn a few echo tricks.

Adding text and variables together:


    <?php

    $name = "Gagan";
    $age = 22;

    echo "My name is " . $name . " and I am " . $age . " years old.";

The dot is the concatenation operator in PHP. It joins strings together. Think of it like glue — it sticks pieces of text together.

Output: My name is Gagan and I am 22 years old.

A cleaner way using double quotes:


    <?php

    $name = "Gagan";
    $age = 22;

    echo "My name is $name and I am $age years old.";

When you use double quotes, PHP automatically replaces variable names inside the string with their values. This is called variable interpolation. Single quotes do not do this — they print the variable name literally.

Try this and see the difference:


    <?php

    $city = "Delhi";

    echo "I live in $city";
    echo "<br>";
    echo 'I live in $city';

First line outputs: I live in Delhi

Second line outputs: I live in $city

The <br> is an HTML line break — it pushes the next output to a new line in the browser.


PHP is Loosely Typed — What Does That Mean?

In some languages, you must declare what type a variable is before using it. PHP does not require this. You just assign a value and PHP figures out the type automatically.


    <?php

    $value = 10;
    echo $value + 5;

    $value = "Hello";
    echo $value;

First echo gives 15. Second echo gives Hello. The same variable held an integer and then a string — PHP allowed it without complaint.

This makes PHP beginner-friendly, but it also means you need to be careful. If you accidentally store "50" as a string and try to do math with it, PHP will usually handle it correctly, but not always. We will cover type handling properly when we get to functions.


A Real World Example — Putting It All Together

Let us build something slightly real. A simple user profile display.

Create a new file in your phplearning folder. Name it profile.php. Write this:


    <!DOCTYPE html>
    <html>

    <head>
        <title>User Profile</title>
    </head>

    <body>

        <?php

        $name = "Gagan";
        $age = 22;
        $city = "Delhi";
        $is_premium = true;
        $balance = 1250.75;

        echo "<h1>Welcome, $name!</h1>";
        echo "<p>Age: $age</p>";
        echo "<p>City: $city</p>";
        echo "<p>Account Balance: Rs. $balance</p>";

        if ($is_premium) {
            echo "<p>Account Type: Premium</p>";
        } else {
            echo "<p>Account Type: Free</p>";
        }

        ?>

    </body>

    </html>

Visit http://localhost:8080/phplearning/profile.php in your browser.

You will see a simple profile page displaying all the variable values. The if/else block checks the boolean and shows different text based on whether the user is premium or not. We will go deep into if/else in Episode 05 — for now just notice how a boolean value controls what gets displayed.


Checking What Type a Variable Is

PHP gives you a built-in tool called var_dump() that shows you the value and the data type of any variable. This is extremely useful when debugging.


    <?php

    $name = "Gagan";
    $age = 22;
    $price = 99.99;
    $active = true;

    var_dump($name);
    echo "<br>";
    var_dump($age);
    echo "<br>";
    var_dump($price);
    echo "<br>";
    var_dump($active);

Output will look like this:

string(5) "Gagan"

int(22)

float(99.99)

bool(true)

var_dump tells you the type and the value together. You will use this constantly while learning PHP to understand what is actually stored inside a variable.


What Did We Learn in This Post?

Variables are labeled containers that store information. In PHP, every variable starts with a dollar sign.

PHP has four basic data types: string for text, integer for whole numbers, float for decimal numbers, and boolean for true or false.

The dot operator joins strings together. Double quotes allow you to embed variables directly inside text.

PHP is loosely typed — you do not need to declare types, PHP figures them out automatically.

var_dump() shows you the type and value of any variable and is your best friend while debugging.


What is Coming in Episode 04?

Next, we cover operators and expressions — how PHP does math, compares values, and combines conditions. We will also cover string functions: built-in tools PHP gives you to manipulate text, like making text uppercase, counting characters, and finding words inside a string.

See you in the next one.


Next Episode: Operators and String Functions — Making PHP Do the Work For You

This is Episode 03 of the PHP and Laravel — Zero to Hero series.

PHP & Laravel — Zero to Hero Episode 02: Setting Up PHP on Windows and Your First PHP Program

What Are We Doing in This Post?

In Episode 01, we understood what PHP is and why we are learning it. Now it is time to actually get our hands dirty.

By the end of this post, you will have:

  • PHP running on your Windows machine
  • A local development server set up
  • VS Code installed and ready
  • Your very first PHP program written and running

Let us get started.


Step 1 — Install XAMPP (PHP + Server in One Package)

On Windows, the easiest way to get PHP running is through a tool called XAMPP.

Here is what XAMPP actually is.

Remember the restaurant analogy from Episode 01? PHP is the kitchen. But a kitchen needs a building to sit inside. That building is a web server — specifically, Apache. XAMPP gives you PHP and Apache together in one installation. One download, one install, everything works.

XAMPP also includes MySQL, which is the database system we will use later in this course.

How to install XAMPP:

Go to this website in your browser: apachefriends.org

Click the big Download button for Windows. The file will be around 150 MB. Once it downloads, open the installer and follow these steps:

Run the installer as Administrator. Right-click the downloaded file and select "Run as administrator."

When the installer asks which components to install, make sure these three are checked: Apache, MySQL, PHP. You can uncheck everything else if you want — FileZilla, Mercury, Tomcat are not needed for this course.

Choose the installation folder. The default is C:\xampp — keep it as is. Do not change it to Program Files because that folder has permission restrictions that can cause problems later.

Click Next and let the installation finish. It takes about two to three minutes.


Step 2 — Start Apache (Your Local Web Server)

After installation, XAMPP will open the XAMPP Control Panel. This is your dashboard for starting and stopping services.

You will see a list of services: Apache, MySQL, FileZilla, Mercury, Tomcat.

Click the Start button next to Apache.

If Apache starts successfully, the row will turn green and you will see port numbers like 80 and 443 appear next to it.

Now open your browser and go to: http://localhost

If you see the XAMPP welcome page, congratulations — your local web server is running. Your computer is now acting like a mini web server, just like the ones that host real websites on the internet.

What is localhost?

Localhost is just a name that means "this computer." When you type http://localhost in your browser, you are visiting a website that is running on your own machine — not on the internet. Only you can see it. This is your safe development environment.


Step 3 — Install VS Code

If you already installed VS Code after Episode 01, skip this step.

Go to code.visualstudio.com and download the Windows installer. Run it and follow the default installation steps.

After installing, open VS Code. It will look empty right now — that is fine.

One extension to install right now:

Inside VS Code, click the Extensions icon on the left sidebar (it looks like four squares). Search for PHP Intelephense and install it. This extension gives you autocomplete, error highlighting, and code hints for PHP. It will make your life much easier.


Step 4 — Find Your PHP Folder

When XAMPP installs, it creates a special folder on your computer:

C:\xampp\htdocs

This folder is the root of your local web server. Any file you put inside this folder can be accessed through your browser using localhost.

Think of it this way. If a real website's files live on a server somewhere in the world, your htdocs folder is that server — but it lives on your own computer.

Open File Explorer and navigate to C:\xampp\htdocs. You will see some files already there — those are XAMPP's default files. Leave them alone.

Create a new folder inside htdocs. Name it: phplearning

This is where all your practice files for this course will live.


Step 5 — Write Your First PHP Program

This is the moment. Let us write actual PHP code.

Open VS Code. Go to File, then Open Folder, and open the phplearning folder you just created at C:\xampp\htdocs\phplearning.

Create a new file inside this folder. Name it: index.php

Now type this code exactly as shown:


    <?php

    echo "Hello, World! My PHP is working.";

    ?>

Save the file. Now open your browser and go to:

http://localhost/phplearning/index.php

You should see this text on the screen:

Hello, World! My PHP is working.

That is it. That is PHP running on your computer. You just wrote and executed your first PHP program.


Understanding What You Just Wrote

Let us break down those three lines.

<?php

This is the PHP opening tag. It tells the server: "Hey, everything from here onwards is PHP code. Process it."

echo "Hello, World! My PHP is working.";

echo is a PHP command that means "print this to the screen." Whatever you put inside the quotes gets displayed in the browser. The semicolon at the end is mandatory in PHP — every statement must end with a semicolon.

?>

This is the PHP closing tag. It tells the server: "PHP code ends here."

Every PHP file follows this basic structure. Opening tag, your code, closing tag.


A Real World Analogy for How PHP Works

Here is exactly what happened when you visited that URL in your browser.

You typed http://localhost/phplearning/index.php and pressed Enter.

Your browser sent a request to your local Apache web server — the one running through XAMPP.

Apache looked at the file you requested. It saw the .php extension and said: "This is a PHP file. I need to hand it to the PHP engine."

The PHP engine read your code, executed the echo statement, and produced plain HTML output: Hello, World! My PHP is working.

Apache sent that HTML back to your browser.

Your browser displayed it.

You never saw the PHP code. The browser only ever sees the final HTML output. This is what server-side means — the processing happens on the server, not in the browser.


Let Us Try a Few More Things

Now that the basics are working, let us explore a little.

Experiment 1 — PHP and HTML together

Replace everything in your index.php file with this:


    <!DOCTYPE html>
    <html>

    <head>
        <title>My First PHP Page</title>
    </head>

    <body>

        <h1><?php echo "Welcome to my PHP page!"; ?></h1>
        <p>Today's date is: <?php echo date("d F Y"); ?></p>

    </body>

    </html>

Save it and refresh your browser at http://localhost/phplearning/index.php

You will see a heading and today's actual date displayed dynamically. PHP calculated the current date for you automatically.

This is the power of PHP mixed with HTML. Static HTML just shows fixed content. PHP inside HTML makes it dynamic — the content can change based on logic, data, or time.

Experiment 2 — PHP doing math

Add this line inside your PHP section:


    <?php echo 10 + 25; ?>

PHP will calculate 10 + 25 and display 35 in the browser. The browser does not see the math — it only sees the result. PHP did the calculation on the server.


Common Errors Beginners Face (And How to Fix Them)

Before we close this episode, let us talk about errors you might run into.

Apache does not start — port conflict

If Apache shows red in the XAMPP Control Panel and does not start, it usually means another program is already using port 80. This is often Skype or IIS (Windows web server).

Fix: In the XAMPP Control Panel, click Config next to Apache, then click httpd.conf. Find the line that says Listen 80 and change it to Listen 8080. Save the file and restart Apache. Now access your site at http://localhost:8080 instead of http://localhost.

Page shows PHP code instead of output

If your browser shows the raw PHP code instead of running it, it means you opened the file directly from File Explorer instead of through localhost. Always access PHP files through http://localhost/... — never by double-clicking the file.

Blank white page

This usually means there is a syntax error in your PHP code — a missing semicolon, an unclosed quote, or a typo. Check your code carefully. We will learn about proper error reporting in the next episode.


What Did We Learn in This Post?

Let us quickly recap everything covered.

You installed XAMPP, which gives you Apache (web server), PHP, and MySQL in one package.

You started Apache and confirmed your local server is working by visiting http://localhost.

You installed VS Code with the PHP Intelephense extension for a proper coding environment.

You learned that C:\xampp\htdocs is your local server's root folder — files here are accessible via http://localhost.

You wrote your first PHP program using the echo command and understood how PHP runs on the server and sends HTML to the browser.

You mixed PHP with HTML to create dynamic content, including displaying today's date automatically.


What is Coming in Episode 03?

Now that your environment is set up, we go into Core PHP properly.

Episode 03 covers: variables, data types, and how PHP stores and works with information. We will build real examples — like storing a user's name and displaying a personalized greeting — so every concept has a practical purpose.

See you in the next one.


Next Episode: PHP Variables, Data Types, and How PHP Thinks About Data

This is Episode 02 of the PHP and Laravel — Zero to Hero series. Follow the blog so you do not miss an episode.

PHP & Laravel — Zero to Hero Episode 01: Before We Write a Single Line of Code

Why This Course Exists

If you search "best backend language to learn in 2025," you will get a hundred different answers. Some say Python. Some say Node.js. Some say Go. But quietly, powering over 77% of all websites on the internet, PHP keeps working — no drama, no hype, just results.

This course exists because PHP with Laravel is one of the most practical, job-ready skill combinations you can learn today. And there are very few courses that actually start from zero — real zero, no assumptions.

That is what we are going to do here.


What is PHP, and Why Should You Care?

PHP stands for Hypertext Preprocessor. That sounds fancy, but the idea is simple.

PHP is a server-side scripting language. This means PHP runs on the server — the computer that stores your website — not inside your browser.

Here is a real-world analogy to make this crystal clear.

Think of the internet as a restaurant.

The customer sitting at the table is your browser. You (the customer) look at the menu and place an order. That order is your HTTP request — basically, you typing a URL and pressing Enter.

The waiter who takes your order to the kitchen is the web server. It carries your request from the browser to the server.

The kitchen is where PHP lives. The chef (PHP) receives the order, checks what ingredients are available (the database), cooks the food (processes your data), and sends the final dish back to the waiter, who delivers it to you.

What you see on your screen — your name, your profile, your order history — that is the dish PHP cooked.

Without PHP (or a similar language), every website would be a static page. No login. No personalization. No shopping cart. Just flat HTML.


Okay, But Why Not Python or Node.js?

Totally fair question.

Python is great. Node.js is great. But here is the honest answer:

PHP was built specifically for the web. It does one thing and does it extremely well. The syntax is beginner-friendly, the job market is massive, hosting is cheap and widely available, and Laravel — the framework we will learn — is considered one of the most elegant frameworks in any language, not just PHP.

Also, WordPress runs on PHP. WooCommerce runs on PHP. Millions of real businesses run on PHP. If you want to build web applications, get freelance clients, or land a backend job, PHP with Laravel is a rock-solid choice.


So What is Laravel?

If PHP is the kitchen, Laravel is the professional chef's toolkit.

You could cook without it. A raw pan, raw fire, raw ingredients. You would eventually get food on the table. But a professional kitchen has pre-measured spoons, labeled containers, organized stations, and a system that makes cooking faster and cleaner.

Laravel is that system.

It is a framework built on top of PHP. It gives you ready-made tools for things every web application needs — user login, database access, form handling, sending emails, security, and much more. You write less code, make fewer mistakes, and build faster.

Laravel is the most popular PHP framework in the world, with millions of developers and a massive community.


Who is This Course For?

This course is for you if:

  • You have never written a single line of PHP
  • You know a little HTML and CSS but nothing about the backend
  • You have tried learning PHP before but gave up because tutorials assumed too much
  • You want to build real web applications, not just follow copy-paste tutorials

You do not need to be a programmer. You do not need a computer science degree. You need curiosity and the willingness to practice.


What Do You Need Before Starting?

You do not need to be an expert in any of these. A basic awareness is enough.

1. Basic HTML and CSS You should know what a tag looks like. Something like this:

<h1>Hello World</h1>

That is it. You do not need to be a CSS wizard.

2. The Concept of a Database Just know this: a database is like an Excel sheet with rows and columns, stored on a server. We will cover MySQL in full detail during the course.

3. Basic Terminal Usage You should be able to open a terminal (Command Prompt on Windows, Terminal on Mac/Linux) and type a command like:

cd my-folder

That is genuinely all. We will cover everything else together.


What Will You Build by the End?

By the time this course is complete, you will have built a full real-world web application using Laravel — something like a blog platform, a job board, or a mini e-commerce store. You will handle user registration, login, database management, file uploads, and deployment on a live server.

Not a toy project. A real one.


The Full Course Roadmap

Here is what the complete journey looks like, phase by phase.

Phase 1 — Core PHP (The Foundation) Variables, data types, conditionals, loops, functions, arrays, working with forms, sessions, file handling, object-oriented programming basics, and connecting PHP to a MySQL database.

Phase 2 — Laravel Basics (The Framework) Installation and setup, understanding MVC architecture, routing, Blade templates, controllers, Eloquent ORM, migrations, and form handling.

Phase 3 — Laravel Intermediate (Going Deeper) User authentication, authorization, middleware, file uploads, building REST APIs, database relationships, queues, jobs, and real-world project structure.

Phase 4 — Project and Deployment A complete real-world Laravel project built from scratch, then deployed to a live server so the world can actually see it.


What is Coming in the Next Post?

Episode 02 is where we roll up our sleeves.

We will install PHP on your machine — whether you are on Windows, Mac, or Linux. We will set up a local development server so you can run PHP code on your own computer. And then we will write our very first PHP program.

It will print something on the screen. Small moment, but it will feel like magic the first time.

Before you move to Episode 02, do one thing: Install VS Code if you have not already. It is free, fast, and the most popular code editor in the world. Download it from code.visualstudio.com.


Next Episode: Setting Up PHP on Your Machine and Your First PHP Program

This is Episode 01 of the PHP and Laravel — Zero to Hero series. New posts drop every week. Follow the blog so you do not miss an episode.


Interesting Facts About PHP You Must Know

PHP powers a massive chunk of the internet and has been doing so for over three decades. Most developers use it daily without knowing its ba...