PHP Basics: A Beginner’s Guide

Atik Bin Mustafij (Sobuj)
9 min readNov 13, 2024

--

1. Introduction to PHP

What is PHP?

  • PHP, or “PHP: Hypertext Preprocessor”, is a server-side scripting language primarily used to create dynamic content for web pages.
  • Real-Life Analogy: Think of PHP as a waiter in a restaurant. When you make an order, the waiter takes it to the kitchen (server), and brings back your meal (webpage content) to your table (browser).
  • Why PHP? PHP is widely used in industry because it’s easy to learn, has a strong support community, and powers some of the most popular websites, including WordPress sites and Wikipedia.

What PHP Does

  • Handles User Requests: PHP can display personalized content, like showing your profile on a website.
  • Processes Data: PHP can handle tasks such as user authentication, form submissions, and file uploads.
  • Interacts with Databases: PHP works seamlessly with databases, allowing data storage, retrieval, and management.

2. Setting Up Your PHP Environment

Local Server Setup:

  • Tools: Install XAMPP (Windows, Linux) or MAMP (Mac) as a local server to run PHP on your computer.
  • Why a Local Server? A local server acts as a “private kitchen” where you can test and experiment with your PHP code before putting it on a live website.

Installation Steps:

  1. Download XAMPP or MAMP.
  2. Follow the installation instructions.
  3. Start the Apache server in XAMPP/MAMP and set up a project folder in the htdocs directory (e.g., htdocs/my_php_project).

Text Editor Setup:

  • Tool: Install VS Code or another preferred text editor.
  • Why a Text Editor? This is where you’ll write and test your PHP code. VS Code is popular because of its helpful features like syntax highlighting and extensions.

3. PHP Syntax Basics

PHP Tags

  • Definition: PHP code is enclosed within <?php ... ?> tags, allowing the server to interpret the code.
  • Example:
<?php
echo "Hello, World!";
?>
  • Real-Life Comparison: PHP tags are like quotation marks in writing — they define where the PHP code “speaks” within your HTML.

Semicolons (;) in PHP

  • Usage: Every PHP statement ends with a semicolon (;), similar to how sentences end with periods in English.
  • Example:
<?php
echo "Hello, World!";
echo "Welcome to PHP!";
?>
  • Best Practice: Always use semicolons to avoid syntax errors, making your code cleaner and easier to debug.

Basic Output with echo and print

  • echo: A common function to output text or variables. Fast and widely used.
  • print: Similar to echo but returns a value, making it slightly slower. Useful in specific contexts, like conditional outputs.
  • Example:
<?php
echo "Hello, World!";
print "Learning PHP is fun!";
?>
  • Best Practice: Use echo when you simply need to display text; use print if you need a return value.

4. Writing Your First PHP Code

Displaying “Hello, World!”

  • Why This Matters: This is a universal programming beginner step to verify your setup is working.
  • Example:
<?php
echo "Hello, World!";
?>
  • Real-Life Comparison: Like greeting someone when you meet them, this code “greets” your browser.

Arithmetic in PHP

  • Basic Operations: PHP supports arithmetic operations, including addition, subtraction, multiplication, and division.
  • Example:
<?php

// Arithmetic Operators in PHP

// Addition (+)
$a = 10;
$b = 20;
$sum = $a + $b; // $sum will be 30
// Output the result
echo "Addition: $a + $b = $sum<br>";

// Subtraction (-)
$c = 15;
$d = 5;
$difference = $c - $d; // $difference will be 10
// Output the result
echo "Subtraction: $c - $d = $difference<br>";

// Multiplication (*)
$e = 7;
$f = 6;
$product = $e * $f; // $product will be 42
// Output the result
echo "Multiplication: $e * $f = $product<br>";

// Division (/)
$g = 50;
$h = 5;
$quotient = $g / $h; // $quotient will be 10
// Output the result
echo "Division: $g / $h = $quotient<br>";

// Modulus (%) - returns the remainder of a division
$i = 25;
$j = 4;
$remainder = $i % $j; // $remainder will be 1
// Output the result
echo "Modulus: $i % $j = $remainder<br>";

// Exponentiation (**)
$k = 3;
$l = 4;
$power = $k ** $l; // $power will be 3^4 = 81
// Output the result
echo "Exponentiation: $k ** $l = $power<br>";

// Combining arithmetic operators
$m = 10;
$n = 3;
$combined_result = ($m + $n) * ($m - $n); // Combined result will be (10 + 3) * (10 - 3) = 91
// Output the result
echo "Combined arithmetic operations result: ($m + $n) * ($m - $n) = $combined_result<br>";

// Increment Operator (++)
$p = 5;
$p++; // $p will be incremented by 1, so it becomes 6
// Output the result
echo "Increment: 5 incremented by 1 is $p<br>";

// Decrement Operator (--)
$q = 10;
$q--; // $q will be decremented by 1, so it becomes 9
// Output the result
echo "Decrement: 10 decremented by 1 is $q<br>";

?>
  • Best Practice: Use descriptive variable names ($price, $quantity) that clearly describe what the value represents, making your code readable and maintainable.

5. Variables in PHP

What are Variables?

  • Definition: Variables are like labeled containers for storing data that can be reused throughout your program.
  • Real-Life Analogy: Think of variables as storage boxes in a warehouse — each box has a label (name) and can store something (value).
  • Example:
<?php
$name = "Alice";
$age = 25;
?>

5.1- Rules for Declaring Variables

Variable Declaration Format

  • Variables in PHP start with a dollar sign ($), followed by the variable name.
  • Example:
$name = "Alice";

Variable Naming Rules

  • Must begin with a letter or underscore (_), not a number.
  • Can contain letters, numbers, and underscores (_), but no spaces or special characters (e.g., @, #, !).
  • Case-sensitive: $name and $Name are treated as different variables in PHP.

Assignment

  • Variables can be assigned a value using the assignment operator (=).
  • Example:
$age = 30;

5.2- Industry Standards and Best Practices for Variable Naming

1. Use Descriptive Names

  • Purpose: Choose names that clearly describe the data the variable holds, improving readability.
  • Examples:
$userName = "Alice";   // Good: Describes the variable clearly
$age = 25; // Good: Describes the variable clearly

2. Use Camel Case for Multi-Word Variable Names

  • Format: Start the first word with lowercase, and capitalize the first letter of each subsequent word.
  • Examples:
$userFirstName = "Alice";   // Camel case
$orderTotal = 150.00; // Camel case

3. Avoid Single-Letter or Ambiguous Names

  • Avoid names like $a, $b, $data, or $var unless they are used in a very limited scope (e.g., in a loop).
  • Example:
$productPrice = 19.99; // Good: Clear and descriptive
$p = 19.99; // Not recommended: Vague and unclear

4. Use Meaningful Prefixes for Boolean Variables

  • Prefix boolean variables with is, has, should, or can to indicate they hold a true/false value.
  • Examples:
$isUserLoggedIn = true;
$hasPaid = false;

5. Avoid Abbreviations or Acronyms

  • Avoid shortening words in ways that might make the code harder to understand for others.
  • Example:
$customerAddress = "123 Main St"; // Good: Clear
$custAddr = "123 Main St"; // Not recommended: Ambiguous

6. Use Constants for Fixed Values

  • If a value will not change (such as a tax rate or base URL), use a constant instead of a variable. Constants are written in all uppercase with underscores between words.
  • Example:
define("TAX_RATE", 0.07);
define("BASE_URL", "https://example.com");

7. Scope-Specific Naming

  • For variables within functions or small blocks, use short, descriptive names that reflect their role in the local context. In longer scripts or modules, use more descriptive names.
  • Example:
function calculateDiscount($totalPrice) {
$discount = 0.1 * $totalPrice; // $discount is meaningful in this local scope
return $discount;
}

5.3- Best Practices for Organizing Variables

1. Organize Related Variables Together

  • Group related variables together for better readability. For instance, group user information or product details into an associative array.
  • Example:
$user = [
'firstName' => 'Alice',
'lastName' => 'Smith',
'email' => 'alice@example.com'
];

2. Avoid Hard-Coding Values Directly

  • Use variables for values that might change rather than hard-coding them. This makes the code easier to maintain.
  • Example:
$shippingCost = 5.00; // Good practice
$totalPrice = $itemPrice + $shippingCost;

3. Keep Variables Scoped

  • Limit the scope of variables to where they’re needed (local scope when possible) to prevent unintended changes in other parts of the code.

4. Document Variables with Comments (When Needed)

  • Add comments to clarify the purpose of a variable if its name alone isn’t sufficient, especially in complex code.
  • Example:
$totalItems = 10; // Total number of items in the user's cart

5.4- Code Example Following Best Practices

Here’s an example that incorporates many of these best practices:

<?php

// Define constants
define("BASE_URL", "https://example.com");
define("TAX_RATE", 0.07);

// User information (organized as an array)
$userInfo = [
'firstName' => 'Alice',
'lastName' => 'Johnson',
'isSubscribed' => true
];

// Item prices
$productPrice = 50.00;
$shippingCost = 5.00;

// Calculate total cost including tax
$taxAmount = $productPrice * TAX_RATE;
$totalCost = $productPrice + $shippingCost + $taxAmount;

// Display order summary
echo "Thank you, " . $userInfo['firstName'] . "!<br>";
echo "Product Price: $" . $productPrice . "<br>";
echo "Shipping Cost: $" . $shippingCost . "<br>";
echo "Tax: $" . $taxAmount . "<br>";
echo "Total Cost: $" . $totalCost . "<br>";

?>

Following these rules and best practices for variable naming and organization will make PHP code more readable, maintainable, and consistent with industry standards. It also makes the code easier for others to understand and modify if needed.

6. PHP Data Types

In PHP, variables can hold different types of data. Each data type serves a particular purpose and determines how the value can be used in operations.

6.1- String

  • Description: Used to store a sequence of characters, typically for textual data.
  • Example:
$greeting = "Hello, World!";
  • Usage: Strings are often used to hold words, sentences, or paragraphs, like names, messages, and any textual content.

6.2- Integer

  • Description: Used to store whole numbers without decimal points, either positive or negative.
  • Example:
$age = 25;
  • Usage: Integers are often used for counts, indexing, or calculations where whole numbers are sufficient.

6.3- Float (or Double)

  • Description: Used to store numbers with decimal points.
  • Example:
$price = 19.99;
  • Usage: Floats are typically used for measurements, calculations involving fractions, or currency.

6.4- Boolean

  • Description: Used to store either true or false values.
  • Example:
$isLoggedIn = true;
  • Usage: Booleans are primarily used in conditions to control the flow of code, such as checking if a user is logged in or if a task is complete.

6.5- Array

  • Description: A collection of multiple values stored in a single variable. Arrays can be:
  • Indexed Arrays: Accessed by numeric indices.
  • Associative Arrays: Accessed by named keys.
  • Example:
$fruits = ["Apple", "Banana", "Cherry"]; // Indexed array
$user = ["name" => "Alice", "age" => 30]; // Associative array
  • Usage: Arrays are used to store lists, collections, or any set of related data like product details, user information, or multiple items.

6.6- Object

  • Description: An instance of a class that can contain both data (properties) and functions (methods) related to a specific entity.
  • Example:
class Car {
public $color;
public function setColor($color) {
$this->color = $color;
}
}
$myCar = new Car();
$myCar->setColor("blue");
  • Usage: Objects are used in Object-Oriented Programming (OOP) to create complex structures that represent entities, like cars, users, or products, each with specific attributes and behaviors.

6.7- NULL

  • Description: Represents a variable with no value or one that has been explicitly set to have no value.
  • Example:
$data = NULL;
  • Usage: NULL is often used to reset variables, represent missing values, or check if a variable has a value assigned.

6.8- Resource

  • Description: A special variable that holds a reference to an external resource, such as a file, database connection, or stream.
  • Example:
$file = fopen("example.txt", "r"); // Opens a file resource
  • Usage: Resources are used for handling connections to files, databases, or network streams. PHP functions that interact with these external systems will typically return a resource.

Summary of PHP Data Types

  • Scalar Types: String, Integer, Float, Boolean
  • Compound Types: Array, Object
  • Special Types: NULL, Resource

Each type is used in different contexts depending on the nature of the data and the operations you need to perform. Understanding these data types helps you write efficient, readable, and functional PHP code.

7. Scope: Local and Global Variables

Local Variables

  • Definition: Variables declared inside a function, accessible only within that function.
  • Example:
function greet() {
$message = "Hello, World!";
echo $message;
}
greet();
echo $message; // Error: $message is not accessible here

Global Variables

  • Definition: Variables declared outside functions, accessible throughout the script.
  • Usage in Functions: Use global keyword inside functions to access a global variable.
  • Example:
$greeting = "Hello!";

function showGreeting() {
global $greeting;
echo $greeting;
}

showGreeting(); // Outputs: Hello!

Superglobals:

Built-in variables in PHP like $_POST, $_GET, and $_SESSION that are accessible globally.

8. Constants in PHP

What are Constants?

  • Definition: Constants are fixed values that don’t change once set.
  • Real-Life Example: Think of constants as emergency contact numbers — they are set once and don’t change.
  • Declaration:
define("SITE_NAME", "My Website");
echo SITE_NAME;
  • Best Practice: Use all uppercase letters with underscores for readability (e.g., SITE_NAME).

9. Special Notes and Best Practices

  1. Use camelCase for Variable Names: For readability, start with lowercase, and capitalize each new word.
  • Example: $userFirstName

2. Code Commenting: Use comments to explain complex code or important steps.

  • Example:
// Calculate total price with discount
$totalPrice = $price - $discount;

3. Consistent Naming Conventions: Choose a style and stick with it. Consistency improves code readability and maintainability.

Conclusion and Next Steps

  • Summary: In this article, you learned about PHP syntax, variables, data types, scope, and constants.
  • What’s Next? In the next article, we’ll dive into control structures and functions, the “decision-makers” and “tools” of PHP.
  • For Further Study: Review additional topics like arrays and object-oriented programming as you advance.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Atik Bin Mustafij (Sobuj)
Atik Bin Mustafij (Sobuj)

Written by Atik Bin Mustafij (Sobuj)

Expert Software Developer with a knack for mobile/web applications, database design, and architecture. Proficient in project management and business analysis.

No responses yet

Write a response