Skip to main content
PHP Backend Development Tutorial
CHAPTER 06 Beginner

PHP Variables, Arrays, and Functions

Updated: May 14, 2026
25 min read

# CHAPTER 6

PHP Variables, Arrays, and Functions

1. Introduction

As your backend applications grow, managing data one variable at a time becomes impossible. Imagine trying to store the names of 1,000 registered users in 1,000 separate variables! Furthermore, writing the exact same code repeatedly to validate emails violates the core rule of programming: DRY (Don't Repeat Yourself). In this chapter, we will master Arrays to manage large datasets and Functions to create reusable blocks of logic.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Create and manipulate Indexed Arrays.
  • Build and traverse Associative Arrays (key-value pairs).
  • Write custom PHP Functions with parameters and return values.
  • Understand variable scope within functions.

3. Beginner-Friendly Explanation

An Array is like a medicine cabinet with many shelves. Instead of buying 10 separate small boxes (variables) to hold your pills, you buy one large cabinet (the Array) and put all the pills on different shelves. You can easily loop through the cabinet to find what you need. A Function is like a blender. You build the blender once. Whenever you want a smoothie, you don't rebuild the blender; you just toss in strawberries (Inputs/Parameters), press the button, and it hands you a smoothie (Output/Return Value).

4. Indexed Arrays

An indexed array stores a list of items. The "index" is the numerical position of the item, starting at 0.
php
1234567891011121314
<?php
// Creating an indexed array of colors
$colors = array("Red", "Green", "Blue");
// Modern short syntax:
$colors = ["Red", "Green", "Blue"];

echo "My favorite color is " . $colors[0]; // Outputs: Red

// Adding to an array
$colors[] = "Yellow"; 

// Counting the items
echo count($colors); // Outputs: 4
?>

5. Associative Arrays (Key-Value Pairs)

Instead of relying on a numerical index (0, 1, 2), associative arrays use named "Keys." This is the most common way data is formatted when pulled from a MySQL database!
php
12345678910111213141516
<?php
// Creating an associative array for a User
$user = [
    "username" => "john_doe",
    "email" => "john@example.com",
    "role" => "Admin"
];

// Accessing the data using the Key
echo "User Email: " . $user["email"];

// Looping through an associative array using foreach
foreach ($user as $key => $value) {
    echo $key . " is " . $value . "<br>";
}
?>

6. Functions (Reusable Logic)

To write a function, you use the function keyword, give it a name, define its parameters (inputs), and return an output.
php
12345678910111213141516
<?php
// Defining a custom function
function calculateTotal($price, $tax_rate) {
    $tax_amount = $price * $tax_rate;
    $total = $price + $tax_amount;
    
    return $total; // Sends the result back to the main code
}

// Calling the function (Using the blender)
$shopping_cart = 100;
$ny_tax = 0.08;

$final_price = calculateTotal($shopping_cart, $ny_tax);
echo "Your total is: $" . $final_price;
?>

7. Variable Scope

A major concept in functions is Scope. A variable created *outside* a function cannot automatically be used *inside* the function.
php
12345678
<?php
$discount = 5; // Global variable

function applyDiscount($price) {
    // ERROR: $discount does not exist inside this function!
    // return $price - $discount; 
}
?>

*To fix this, you either pass the discount in as a parameter, or use the global keyword.*

8. Backend Workflow Example: User Verification

Let's combine arrays and functions to simulate checking if a user is banned.
php
1234567891011121314151617181920
<?php
// Simulated database of banned emails
$banned_emails = ["hacker@bad.com", "spam@bot.com"];

function isUserBanned($email_to_check, $banned_list) {
    // in_array() is a built-in PHP function to search an array
    if (in_array($email_to_check, $banned_list)) {
        return true;
    }
    return false;
}

$new_signup = "spam@bot.com";

if (isUserBanned($new_signup, $banned_emails)) {
    echo "Access Denied. You are banned.";
} else {
    echo "Welcome!";
}
?>

9. Best Practices

  • Single Responsibility Principle: A function should do exactly one thing. If your function is called calculateTax(), it should only calculate math. It should *not* also print HTML to the screen. Return the math, and let a different part of your code handle the printing.

10. Common Mistakes

  • echo vs return in Functions: Beginners often echo the result inside the function. This is bad practice because it forces the function to print text immediately, even if you just wanted to save the result to a variable. Always return the value from the function, and echo it outside the function.

11. Exercises

  1. 1. Create an Associative Array representing a Book (Title, Author, Pages). Write a foreach loop to print all the details to the screen.

12. Coding Challenges

  • Challenge: Write a function called celsiusToFahrenheit($temp). It should take a temperature in Celsius, perform the math ($temp * 9/5) + 32, and return the Fahrenheit value. Call the function with the value 20 and echo the result.

13. MCQs with Answers

Question 1

In PHP, what type of array uses named keys (like "email" => "test@test.com") instead of numerical indexes (0, 1, 2)?

Question 2

What keyword is used inside a PHP function to send a value back to the main script?

14. Interview Questions

  • Q: Explain the difference between an Indexed Array and an Associative Array. Which one is more commonly used when fetching a single user row from a database?
  • Q: What is "Variable Scope" in PHP, and why can't a function automatically read a variable declared at the top of your file?

15. FAQs

Q: Can an array hold another array inside it? A: Yes! This is called a Multidimensional Array. It is heavily used in backend development to hold a list of users, where each user is their own associative array.

16. Summary

In Chapter 6, we scaled up our ability to handle data. Arrays allow us to group related pieces of data into single, manageable lists or key-value structures. Functions allow us to encapsulate complex logic into reusable blocks, adhering to the DRY principle. These tools are the absolute prerequisite for handling the massive amounts of data returned by databases.

17. Next Chapter Recommendation

We know how to store data in variables and arrays, but that data disappears when the server turns off. To save data permanently, proceed to Chapter 7: Working with MySQL Databases.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·