PHP Fundamentals: The Building Blocks
9 min read
PHP Fundamentals: The Building Blocks 🧱
Welcome! Ready to lay the foundation for your PHP journey? These next few topics are the absolute bedrock of the language. Understanding them thoroughly is like learning the alphabet before you try to write a novel. It's the essential first step to building anything cool. Let's get to it!
1. Variables and Scope: Storing Data the PHP Way 🏷️
The Problem
Imagine you're building an e-commerce site. You need to remember the user's name, the price of the item they're looking at, and the quantity they want to buy. How do you hold onto this information while your script is running? If you can't store it somewhere, you can't use it. You can't greet the user, you can't calculate the total price—your site is basically a static brochure.
The Solution: Variables!
A variable is a container in your code used to store information. That's it. It's like a labeled box where you can put a piece of data, and you can change what's inside that box later on.
In PHP, a variable always starts with a dollar sign ($). Seriously, always. No dollar sign, no variable. It's the law.
Naming Rules (The Important Stuff):
- Must start with a
$followed by a letter or an underscore. - Can contain letters, numbers, and underscores.
- Cannot start with a number after the
$.$1stPlaceis a no-go.$_1stPlaceis fine. - Variables are case-sensitive.
$nameand$Nameare two completely different boxes. This trips up everyone at some point. You've been warned! 😉
Industry Standard: The common practice is to use camelCase for variable names. It looks like this: $customerFirstName, $itemsInCart.
<?php
// Declaring a variable and assigning a value
$customerName = "Alex";
$itemCount = 5;
$totalPrice = 10.99;
// You can use them later
echo "Welcome, " . $customerName; // Outputs: Welcome, Alex
echo "You have " . $itemCount . " items."; // Outputs: You have 5 items.
// And you can change their values!
$itemCount = $itemCount + 1;
echo "You now have " . $itemCount . " items."; // Outputs: You now have 6 items.
?>A Quick Word on Scope (Keep it Simple)
For now, just remember this: variables defined inside a function only exist inside that function.
Think of it like a private conversation. If you and a friend decide inside a room that "the package" means a box of donuts, anyone outside that room won't have a clue what you're talking about. The meaning is local to the room (the function).
<?php
$outsideVar = "I'm outside the room.";
function myRoom() {
$insideVar = "I'm only available in this room.";
echo $insideVar; // This works fine.
// echo $outsideVar; // This would cause an error!
}
myRoom(); // Outputs: I'm only available in this room.
// echo $insideVar; // This will also cause an error.
?>2. Data Types: Strings, Integers, Booleans, and Beyond 🗂️
The Problem
Okay, so we have our variable "boxes." But what kind of stuff can we put in them? If we have a box for $price and a box for $customerName, the computer needs to know that one holds a number (that we can do math with) and the other holds text (that we can't). If it gets them confused, you might accidentally try to calculate "Alex" * 3, which is... well, nonsense.
The Solution: Data Types
Data types are simply classifications that tell PHP what kind of data a variable holds. PHP is pretty smart and usually figures it out on its own, but you need to know what you're working with. Here are the most common types you'll use 99% of the time.
String: Plain old text. You wrap it in single
'or double"quotes.- Real-world use: Usernames, email addresses, messages, product titles.
php$greeting = "Hello, World!"; $customerEmail = '[email protected]';Integer: A whole number, no decimals.
- Real-world use: Item count, a user's age, number of likes.
php$quantity = 10; $temperature = -5;Float (or Double): A number with a decimal point.
- Real-world use: Prices, ratings, measurements.
php$price = 49.95; $averageRating = 4.7;Boolean (bool): The simplest type. It's either
trueorfalse. That's it. Incredibly important for making decisions in your code.- Real-world use: Is the user logged in?
isLoggedIn = true. Is the product in stock?inStock = false.
php$isUserLoggedIn = true; $productIsOnSale = false;- Real-world use: Is the user logged in?
Array: A special variable that can hold more than one value at a time, like a list.
- Real-world use: A list of products in a shopping cart, a list of user comments.
php$shoppingCart = ["Coffee Beans", "Milk", "Sugar"];NULL: This one is special. It means "nothing." It represents the intentional absence of any value. It's not zero, it's not an empty string, it's just... null.
- Real-world use: A user who hasn't set a profile picture yet might have
$profilePicture = null;.
php$middleName = null;- Real-world use: A user who hasn't set a profile picture yet might have
Funny Business (Under the Hood): PHP is a "loosely typed" language. This means it's pretty relaxed about data types. Sometimes, it tries to be "helpful" in ways that can be confusing.
<?php
$howManyHats = "5"; // This is a string, not a number!
$howManyShirts = 10; // This is an integer.
$totalClothingItems = $howManyHats + $howManyShirts;
echo $totalClothingItems; // Outputs: 15
?>In the example above, PHP saw you trying to add a string "5" to a number 10. It shrugged, converted the string to a number for you, and gave you 15. While this can be handy, it can also lead to unexpected bugs. It's good practice to always be aware of what data types you're working with.
3. Constants: Unchanging Values in Your Code 🏛️
The Problem
Let's say you're building a system and the company's name is "Innovate Corp". You might use this name in the header, the footer, the "About Us" page, etc. What if you store it in a variable, $companyName = "Innovate Corp";? Someone (maybe even you, six months from now) could accidentally write code that changes $companyName to something else halfway through the script. Now your website looks broken. Some values should never, ever change.
The Solution: Constants
A constant is an identifier for a value that cannot be changed during the script's execution. Once you set it, it's set in stone.
Industry Standard: The convention is to name constants in all UPPERCASE_WITH_UNDERSCORES. This makes them easy to spot in your code and reminds you that they are unchangeable.
You can define them in two ways, but const is the more modern and generally preferred way for defining constants at the top level of your code.
<?php
// The modern way (preferred)
const SITE_NAME = "My Awesome Blog";
// The classic way
define("DATABASE_PASSWORD", "s3crEt_p@s5w0rd!");
echo "Welcome to " . SITE_NAME; // Outputs: Welcome to My Awesome Blog
// If you try to do this...
// SITE_NAME = "Your Lame Blog";
// ...PHP will scream at you with a fatal error. And it should!
?>4. Operators: Math, Logic, and Comparisons ⚙️
The Problem
Okay, we've got our data stored in variables and constants. Now what? Data is useless if you can't operate on it. We need a way to do math (calculate a total price), a way to compare things (is the user's password correct?), and a way to combine logical conditions (grant access if the user is an admin or if they are the owner of the post).
The Solution: Operators
Operators are the symbols you use to perform operations. You already know a bunch of these from math class.
Arithmetic Operators (The Usual Suspects)
+Addition-Subtraction*Multiplication/Division%Modulo (This one is fun! It gives you the remainder of a division.10 % 3is1because 3 goes into 10 three times with a remainder of 1. Super useful for figuring out if a number is even or odd).
$subtotal = 100;
$tax = 10;
$total = $subtotal + $tax; // 110Assignment Operators (Helpful Shortcuts)
You'll use = all the time. The others are just shorthand.
=Assign a value:$x = 5;+=Add and assign:$x += 2;(same as$x = $x + 2;)-=Subtract and assign:$x -= 2;(same as$x = $x - 2;).=Concatenate and assign (for strings):$greeting .= " World!";(same as$greeting = $greeting . " World!";)
Comparison Operators (The Heart of Logic)
These always result in a boolean (true or false).
==Equal: Are the values the same? (5 == "5"istrue. Uh oh.)===Identical: Are the values the same AND is the data type the same? (5 === "5"isfalse. Much safer!)!=Not Equal: Are the values different?!==Not Identical: Are the values or the data types different?>,<,>=,<=Greater than, less than, etc.
🚨 Industry Hot Tip: Always default to using the strict === and !== operators. It will save you from countless headaches caused by PHP's loose type juggling. You are comparing both the value and the type, which is almost always what you actually want to do.
Logical Operators (Combining Comparisons)
&&And:trueonly if both conditions are true.||Or:trueif at least one condition is true.!Not: Flips the boolean value.!truebecomesfalse.
<?php
$userAge = 25;
$isPremiumMember = false;
// Example 1: Check for a senior discount
if ($userAge >= 65) {
// give discount
}
// Example 2: Check for access to a special feature
if ($userAge > 18 && $isPremiumMember == true) {
echo "Access granted to premium content!";
}
// Example 3: Check if an order qualifies for free shipping
$orderTotal = 150;
$couponCode = "FREESHIP";
if ($orderTotal > 100 || $couponCode === "FREESHIP") {
echo "You get free shipping!";
}
?>Further Reading & Official Docs 📚
To dive deeper, the official PHP documentation is your best friend. It's the ultimate source of truth.
Challenge
Shopping Cart Calculator
You are tasked with creating a PHP script to calculate the final price of a shopping cart order. You must use variables, constants, and various operators to determine the subtotal, apply a conditional discount, calculate tax, and generate a final summary string.
Requirements:
- Define a constant named
SALES_TAX_RATEwith a value of0.0825. - Using the pre-defined variables, calculate the initial subtotal (unit price multiplied by quantity) and store it in a variable named
$subtotal. - Implement a discount logic. A 15% discount is applied only if the user is a premium member (
$isPremiumMemberistrue) AND the$cartItemCountis greater than or equal to 3. Store the calculated discount amount in a variable named$discountAmount. If no discount is applied, this should be0. - Calculate the total tax. The tax must be calculated on the price after the discount has been subtracted. Store this value in
$taxAmount. Use theSALES_TAX_RATEconstant for the calculation. - Determine the final total cost by taking the subtotal, subtracting the discount, and adding the tax. Store this in
$finalTotal. - Create a summary string named
$receipt. Initialize it with an empty string''. Use the string concatenation assignment operator (.=) to build a receipt that includes the subtotal, discount, tax, and final total, each on a new line and clearly labeled (e.g.,"Subtotal: $...\n").
Note: Use the strict comparison operator (===) where appropriate for robust checks.
Expected result
Your script should correctly define the constant and calculate the values for the specified variables. Based on the initial data:
- A constant
SALES_TAX_RATEmust be defined with the value0.0825. - The
$subtotalvariable should hold the value222.0. - The
$discountAmountvariable should hold the value33.3(15% of 222.0). - The
$taxAmountvariable should hold the value15.56775(8.25% of the post-discount price). - The
$finalTotalvariable should hold the value204.26775. - The
$receiptvariable must be a multi-line string containing neatly labeled lines for the subtotal, discount, tax, and final total.