What is an Array in PHP? See Complete Examples

An array in PHP is a special variable that can hold multiple values under a single name. Instead of creating separate variables for each value, an array lets you store and manage a group of related data efficiently.

Arrays are one of the most important data structures in PHP, widely used for storing lists, user data, records, and configuration values.


Types of Arrays in PHP

PHP supports three main types of arrays:


1. Indexed Array (Numeric Array)

These arrays use numeric indexes, starting from 0.

Example:

$fruits = ["Apple", "Banana", "Cherry"];

echo $fruits[0]; // Output: Apple

2. Associative Array

These arrays use named keys instead of numbers.

Example:

$user = [
    "name" => "Sagar",
    "role" => "Developer",
    "age" => 25
];

echo $user["name"]; // Output: Sagar

3. Multidimensional Array

An array that contains one or more nested arrays.

Example:

$employees = [
    ["John", "Manager"],
    ["Sagar", "Developer"],
    ["Aman", "Designer"]
];

echo $employees[1][1]; // Output: Developer

Why Use Arrays?

  • Store multiple values in a single variable
  • Easily loop through large sets of data
  • Organize and structure information
  • Make functions and logic cleaner and reusable

Common Array Functions

PHP provides many built-in array functions:

FunctionUse
count()Counts number of elements
array_push()Adds values to end
array_pop()Removes last element
array_merge()Combines arrays
in_array()Checks if value exists
array_keys()Returns all keys

Example Using Array Functions:

$numbers = [10, 20, 30];
array_push($numbers, 40);

echo count($numbers); // Output: 4

Example: Simple Array Use Case

$marks = [
    "Math" => 90,
    "English" => 85,
    "Science" => 92
];

foreach ($marks as $subject => $score) {
    echo "$subject: $score <br>";
}

Conclusion

An array in PHP is a powerful structure that allows you to store multiple values, organize data, and perform operations efficiently. Whether you’re handling lists, user profiles, or complex datasets, arrays are essential in PHP development.


Citations

🔗 View other articles about PHP:
http://savanka.com/category/learn/php/

🔗 External PHP Documentation:
https://www.php.net/manual/en/

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *