Paramclasses Academy - Blog

Tutorials Details

←
Post 6 of 15
→

Arrays in PHP With Practical Examples

Arrays in PHP With Practical Examples

October 10, 2026

Title: PHP Arrays Tutorial for Beginners With Examples

Meta Description: Learn PHP arrays from basics, including indexed, associative, and multidimensional arrays, array functions, foreach loops, and real-world examples.

Focus Keyword: PHP Arrays Tutorial for Beginners

Secondary Keywords: PHP Array Examples, Indexed Array in PHP, Associative Array in PHP, Multidimensional Array in PHP, PHP Array Functions, PHP Foreach Loop, Core PHP Tutorial

Suggested URL Slug: php-arrays-tutorial-for-beginners

Introduction to Arrays in PHP

Welcome to Module 6 of our Core PHP Programming Tutorial for Beginners. In this module, we will learn about arrays in PHP, their types, important array functions, and how to use arrays in real-world web applications.

In previous modules, we learned PHP variables, constants, data types, operators, conditional statements, and loops. Now, we will understand how to store and manage multiple values using a single variable.

For example, suppose you are developing a school management system. You need to store the names of 50 students. Creating 50 separate variables would make your code difficult to manage. Instead, you can store all student names in a single array.

PHP arrays are widely used in student management systems, e-commerce websites, news portals, inventory software, billing applications, and other database-driven web applications.

1. What Is an Array in PHP?

An array in PHP is a data structure that allows you to store multiple values in a single variable.

These values can be strings, integers, floats, booleans, objects, or even other arrays.

Example: Without an Array

<?php
$student1 = "Rahul";
$student2 = "Amit";
$student3 = "Priya";

echo $student1;
echo "<br>";
echo $student2;
echo "<br>";
echo $student3;
?>

In this example, each student name is stored in a separate variable.

Example: Using an Array

<?php
$students = ["Rahul", "Amit", "Priya"];

echo $students[0];
echo "<br>";
echo $students[1];
echo "<br>";
echo $students[2];
?>

Output:

Rahul

Amit

Priya

Here, all three student names are stored in a single variable named $students.

The numbers 0, 1, and 2 are array indexes. In this indexed array, indexing starts at 0.

Why do we use arrays in PHP?

  • To store multiple values in one variable.

  • To reduce repetitive code.

  • To manage lists of records.

  • To loop through multiple values easily.

  • To organize data for reports, tables, and applications.

2. Types of Arrays in PHP

PHP commonly uses three types of arrays:

  1. Indexed arrays

  2. Associative arrays

  3. Multidimensional arrays

Let's understand each type with practical examples.

3. Indexed Arrays in PHP

An indexed array stores values using numeric indexes. PHP automatically assigns indexes starting at 0 when you create a conventional indexed array.

Example 1: Creating an Indexed Array

<?php
$fruits = ["Apple", "Banana", "Mango", "Orange"];

echo $fruits[0];
echo "<br>";
echo $fruits[1];
echo "<br>";
echo $fruits[2];
echo "<br>";
echo $fruits[3];
?>

Output:

Apple

Banana

Mango

Orange

Explanation

  • $fruits is the array variable.

  • "Apple" is stored at index 0.

  • "Banana" is stored at index 1.

  • "Mango" is stored at index 2.

  • "Orange" is stored at index 3.

You can access an individual array element using its index.

Example 2: Adding Values to an Array

You can add a new value to an array using the empty square brackets.

<?php
$fruits = ["Apple", "Banana", "Mango"];

$fruits[] = "Orange";

print_r($fruits);
?>

Output:

Array
(
    [0] => Apple
    [1] => Banana
    [2] => Mango
    [3] => Orange
)

The print_r() function displays information about an array in a human-readable format. It is particularly useful when learning and debugging PHP.

Example 3: Updating an Array Value

<?php
$fruits = ["Apple", "Banana", "Mango"];

$fruits[1] = "Grapes";

echo $fruits[1];
?>

Output:

Grapes

The value at index 1 changes from "Banana" to "Grapes".

Real-World Example: Student Names

<?php
$students = ["Rahul", "Amit", "Priya", "Neha"];

foreach ($students as $student) {
    echo $student . "<br>";
}
?>

Real-world application: Indexed arrays can be used to display student names, product lists, available services, menu items, and other simple collections.

4. Associative Arrays in PHP

An associative array stores values using named keys instead of relying only on numeric indexes.

Associative arrays are useful when you want to store related information such as a student's name, age, city, or course.

Example 1: Creating an Associative Array

<?php
$student = [
    "name" => "Rahul",
    "age" => 20,
    "city" => "Raipur",
    "course" => "BCA"
];

echo $student["name"];
echo "<br>";
echo $student["age"];
echo "<br>";
echo $student["city"];
echo "<br>";
echo $student["course"];
?>

Output:

Rahul

20

Raipur

BCA

Explanation

  • "name" is a key that stores the student's name.

  • "age" is a key that stores the student's age.

  • "city" is a key that stores the student's city.

  • "course" is a key that stores the student's course.

To access a value, use its corresponding key inside square brackets.

Example 2: Adding a New Key

<?php
$student = [
    "name" => "Rahul",
    "age" => 20
];

$student["city"] = "Raipur";

echo $student["city"];
?>

Output:

Raipur

Example 3: Updating a Value

<?php
$student = [
    "name" => "Rahul",
    "age" => 20
];

$student["age"] = 21;

echo $student["age"];
?>

Output:

21

Real-World Example: Employee Details

<?php
$employee = [
    "id" => 101,
    "name" => "Amit Sharma",
    "department" => "IT",
    "salary" => 30000
];

echo "Employee ID: " . $employee["id"] . "<br>";
echo "Employee Name: " . $employee["name"] . "<br>";
echo "Department: " . $employee["department"] . "<br>";
echo "Salary: ₹" . $employee["salary"];
?>

Real-world application: Associative arrays are useful for representing employee details, customer profiles, product information, configuration settings, and individual database records.

5. Multidimensional Arrays in PHP

A multidimensional array is an array that contains one or more arrays as its elements.

It is useful when you need to organize multiple records, with each record containing several related values.

For example, a school management system may need to store the names, ages, and courses of several students.

Example 1: Creating a Multidimensional Array

<?php
$students = [
    [
        "name" => "Rahul",
        "age" => 20,
        "course" => "BCA"
    ],
    [
        "name" => "Priya",
        "age" => 21,
        "course" => "MCA"
    ],
    [
        "name" => "Amit",
        "age" => 19,
        "course" => "B.Tech"
    ]
];

echo $students[0]["name"];
echo "<br>";
echo $students[1]["course"];
echo "<br>";
echo $students[2]["age"];
?>

Output:

Rahul

MCA

19

Explanation

  • $students[0] represents the first student record.

  • $students[0]["name"] accesses the first student's name.

  • $students[1]["course"] accesses the second student's course.

  • $students[2]["age"] accesses the third student's age.

The first index selects the student record, and the named key selects a value within that record.

Example 2: Displaying All Student Records

<?php
$students = [
    ["name" => "Rahul", "age" => 20, "course" => "BCA"],
    ["name" => "Priya", "age" => 21, "course" => "MCA"],
    ["name" => "Amit", "age" => 19, "course" => "B.Tech"]
];

foreach ($students as $student) {
    echo "Name: " . $student["name"] . "<br>";
    echo "Age: " . $student["age"] . "<br>";
    echo "Course: " . $student["course"] . "<br><hr>";
}
?>

This program displays the details of all three students.

Real-world application: Multidimensional arrays are useful for representing collections of students, employees, products, invoices, and other structured records before or after database processing.

6. Important Array Functions in PHP

PHP provides built-in functions to make array operations easier. These functions help developers count elements, add or remove values, search for information, sort data, and combine arrays.

6.1 count()

The count() function returns the number of elements in an array.

<?php
$fruits = ["Apple", "Banana", "Mango", "Orange"];

echo count($fruits);
?>

Output:

4

Use: Counting the number of products, students, or items in a list.

6.2 array_push()

The array_push() function adds one or more values to the end of an array.

<?php
$fruits = ["Apple", "Banana"];

array_push($fruits, "Mango", "Orange");

print_r($fruits);
?>

Output:

Array
(
    [0] => Apple
    [1] => Banana
    [2] => Mango
    [3] => Orange
)

Use: Adding new items to an existing list.

6.3 array_pop()

The array_pop() function removes and returns the last element of an array.

<?php
$fruits = ["Apple", "Banana", "Mango"];

array_pop($fruits);

print_r($fruits);
?>

Output:

Array
(
    [0] => Apple
    [1] => Banana
)

Use: Removing the last item from a list.

6.4 array_merge()

The array_merge() function combines arrays.

<?php
$array1 = ["Apple", "Banana"];
$array2 = ["Mango", "Orange"];

$result = array_merge($array1, $array2);

print_r($result);
?>

Output:

Array
(
    [0] => Apple
    [1] => Banana
    [2] => Mango
    [3] => Orange
)

Use: Combining product lists, categories, or collections of values.

6.5 in_array()

The in_array() function checks whether a value exists in an array.

<?php
$fruits = ["Apple", "Banana", "Mango"];

if (in_array("Banana", $fruits, true)) {
    echo "Fruit found";
} else {
    echo "Fruit not found";
}
?>

Output:

Fruit found

The third argument, true, enables strict comparison.

Use: Checking whether a value appears in a list. In real applications, authorization and security checks should use reliable server-side data rather than relying on a simple array membership check alone.

6.6 sort()

The sort() function sorts an array in ascending order and reindexes its elements.

<?php
$numbers = [50, 10, 40, 20, 30];

sort($numbers);

print_r($numbers);
?>

Output:

Array
(
    [0] => 10
    [1] => 20
    [2] => 30
    [3] => 40
    [4] => 50
)

Use: Sorting numbers or values in a simple indexed array.

6.7 rsort()

The rsort() function sorts an array in descending order and reindexes its elements.

<?php
$numbers = [10, 50, 20, 40, 30];

rsort($numbers);

print_r($numbers);
?>

Output:

Array
(
    [0] => 50
    [1] => 40
    [2] => 30
    [3] => 20
    [4] => 10
)

Use: Sorting numeric values from highest to lowest.

6.8 array_keys()

The array_keys() function returns the keys of an array.

<?php
$student = [
    "name" => "Rahul",
    "age" => 20,
    "city" => "Raipur"
];

print_r(array_keys($student));
?>

Output:

Array
(
    [0] => name
    [1] => age
    [2] => city
)

Use: Finding the keys defined in an associative array.

6.9 array_values()

The array_values() function returns all values from an array in a numerically indexed array.

<?php
$student = [
    "name" => "Rahul",
    "age" => 20,
    "city" => "Raipur"
];

print_r(array_values($student));
?>

Output:

Array
(
    [0] => Rahul
    [1] => 20
    [2] => Raipur
)

Use: Extracting the values from an associative array.

6.10 array_sum()

The array_sum() function calculates the sum of the values in an array.

<?php
$marks = [80, 75, 90, 85];

echo array_sum($marks);
?>

Output:

330

Use: Calculating total marks, quantities, or other numeric totals.

7. Using foreach With PHP Arrays

The foreach loop is one of the easiest ways to access every element in an array.

It works with indexed arrays, associative arrays, and multidimensional arrays.

Example 1: foreach With an Indexed Array

<?php
$fruits = ["Apple", "Banana", "Mango"];

foreach ($fruits as $fruit) {
    echo $fruit . "<br>";
}
?>

Output:

Apple

Banana

Mango

Example 2: foreach With an Associative Array

<?php
$student = [
    "name" => "Rahul",
    "age" => 20,
    "city" => "Raipur"
];

foreach ($student as $key => $value) {
    echo $key . ": " . $value . "<br>";
}
?>

Output:

name: Rahul

age: 20

city: Raipur

Here, $key stores the current key, while $value stores the corresponding value.

Real-World Example: Displaying Product Names

<?php
$products = [
    "Laptop",
    "Keyboard",
    "Mouse",
    "Monitor"
];

echo "<h2>Available Products</h2>";

foreach ($products as $product) {
    echo "<p>" . htmlspecialchars($product, ENT_QUOTES, "UTF-8") . "</p>";
}
?>

Real-world application: The foreach loop is commonly used to display database results, products, students, employees, and other collections of records.

8. Real-World Project Example: Product Management Using Arrays

Let's create a simple product list similar to the data displayed in an e-commerce website.

In this example, each product contains a name, price, and quantity.

<?php
$products = [
    [
        "name" => "Keyboard",
        "price" => 650,
        "quantity" => 5
    ],
    [
        "name" => "Mouse",
        "price" => 350,
        "quantity" => 10
    ],
    [
        "name" => "Monitor",
        "price" => 7500,
        "quantity" => 3
    ]
];

echo "<h2>Product Management System</h2>";

foreach ($products as $product) {
    echo "<h3>" .
        htmlspecialchars($product["name"], ENT_QUOTES, "UTF-8") .
        "</h3>";

    echo "Price: ₹" . $product["price"] . "<br>";
    echo "Available Quantity: " . $product["quantity"] . "<br>";

    $totalValue = $product["price"] * $product["quantity"];

    echo "Stock Value: ₹" . $totalValue . "<hr>";
}
?>

Expected Output

Keyboard

Price: ₹650

Available Quantity: 5

Stock Value: ₹3250

Mouse

Price: ₹350

Available Quantity: 10

Stock Value: ₹3500

Monitor

Price: ₹7500

Available Quantity: 3

Stock Value: ₹22500

How Does This Program Work?

  1. The $products array stores multiple product records.

  2. Each product is represented by an associative array.

  3. The foreach loop processes each product.

  4. The program displays the product name, price, and quantity.

  5. The total stock value is calculated by multiplying price by quantity.

How Can This Be Used in a Real Application?

This basic example can be extended into a complete inventory management system with database integration, product registration, stock updates, search filters, and reports.

In a production application, persistent product data would generally be stored in a database such as MySQL rather than only in a PHP array.

9. Difference Between Indexed, Associative, and Multidimensional Arrays

Feature Indexed Array Associative Array Multidimensional Array
Keys Numeric indexes Named or other explicit keys Keys at multiple levels
Example ["Apple", "Mango"] ["name" => "Rahul"] [["name" => "Rahul"]]
Access $arr[0] $arr["name"] $arr[0]["name"]
Best suited for Simple lists Related named values Collections of structured records
Real-world example Fruit list Employee details List of employees

10. Best Practices for Using Arrays in PHP

Follow these practices while developing PHP applications:

  1. Use meaningful variable names such as $students or $products.

  2. Choose indexed arrays for simple lists and associative arrays for named information.

  3. Use multidimensional arrays when records contain multiple related fields.

  4. Use foreach to iterate through array elements.

  5. Check whether a key exists with array_key_exists() when necessary.

  6. Use isset() when you need to check whether a value exists and is not null.

  7. Use strict comparisons where appropriate, such as in_array($value, $array, true).

  8. Escape untrusted text before displaying it in HTML.

  9. Validate input before using it in calculations or database operations.

  10. Use a database for persistent application records rather than relying on arrays alone.

11. Practice Exercises for PHP Arrays

Try the following exercises to improve your PHP programming skills.

Exercise 1: Fruit List

Create an indexed array containing five fruit names and display all values using foreach.

Exercise 2: Student Details

Create an associative array containing a student's name, age, city, and course.

Exercise 3: Employee Records

Create a multidimensional array containing three employees, including their names, departments, and salaries.

Exercise 4: Count Array Elements

Create an array of ten numbers and use count() to display the number of elements.

Exercise 5: Add and Remove Values

Create an array of products. Add one product using array_push() and remove the last product using array_pop().

Exercise 6: Search an Array

Create an array of city names and use in_array() to check whether "Raipur" exists.

Exercise 7: Calculate Total Marks

Create an array of five subject marks and calculate the total using array_sum().

Exercise 8: Sort Numbers

Create an array of numbers and sort them in ascending and descending order using sort() and rsort().

Exercise 9: Product List

Create a multidimensional array containing product names, prices, and quantities. Display all products using foreach.

Exercise 10: Student Report

Create a multidimensional array containing student names and marks. Display a report showing each student's details and total marks.

12. Frequently Asked Questions About PHP Arrays

What is an array in PHP?

An array is a data structure that stores multiple values in a single variable. It can contain strings, numbers, booleans, objects, and other arrays.

What are the three main types of arrays in PHP?

The three commonly taught array types are indexed arrays, associative arrays, and multidimensional arrays.

What is an indexed array in PHP?

An indexed array uses numeric indexes to access values. For example, $fruits[0] accesses the first element of a conventional indexed array.

What is an associative array in PHP?

An associative array stores values using keys. For example, $student["name"] accesses the value associated with the "name" key.

What is a multidimensional array in PHP?

A multidimensional array contains other arrays. It is useful for storing collections of records, such as multiple students or products.

What is the use of foreach in PHP?

The foreach loop iterates through array elements without requiring you to manually manage an index for every iteration.

What is the difference between count() and sizeof()?

Both count() and sizeof() can return the number of elements in an array. sizeof() is an alias of count(). Beginners can use count() for clarity.

Can PHP arrays store different data types?

Yes. A PHP array can contain different data types, including strings, integers, floats, booleans, objects, and other arrays.

Can PHP arrays be used with MySQL?

Yes. PHP arrays are frequently used to process data retrieved from MySQL queries. They can also be used to prepare collections of values for display, validation, and other operations.

Conclusion

PHP arrays are an essential part of Core PHP programming. They allow developers to store, organize, search, update, and process multiple values efficiently.

In this tutorial, we covered indexed arrays, associative arrays, multidimensional arrays, important array functions, foreach loops, and practical examples involving student records and product management.

By practicing these concepts, you will develop the skills needed to manage collections of data in dynamic websites and web applications.

Start by creating simple arrays and displaying their values. Then practice array functions and multidimensional arrays before moving on to database-driven projects.

←
Post 6 of 15
→