Current Location: Home> Latest Articles> 【Beginner's Guide】Understanding PHP Arrays: Definition, Access, and Common Operations

【Beginner's Guide】Understanding PHP Arrays: Definition, Access, and Common Operations

gitbox 2025-06-07

1. What Is a PHP Array?

In PHP, an array is a data structure that stores multiple values in a single variable. Arrays can hold values of different types such as strings, integers, floats, objects, or even other arrays.

1.1 How to Define an Array in PHP

There are two primary ways to define an array in PHP:

  • Using the array() function
  • Using short array syntax with square brackets

$fruits = array("apple", "orange", "banana");

Or using the modern syntax:


$fruits = ["apple", "orange", "banana"];

1.2 Accessing Elements in an Array

You can access elements in an array using their index. Array indexes start from 0:


echo $fruits[0]; // Outputs "apple"

2. Common Array Operations in PHP

2.1 Looping Through an Array

The foreach loop is the most common way to iterate through an array:


foreach ($fruits as $fruit) {
    echo $fruit;
}

Output:

apple
orange
banana

You can also retrieve both the keys and values during iteration:


foreach ($fruits as $key => $value) {
    echo "Key: " . $key . ", Value: " . $value;
}

Output:

Key: 0, Value: apple
Key: 1, Value: orange
Key: 2, Value: banana

2.2 Adding Elements to an Array

You can add new elements to the end of an array using the following syntax:


$fruits[] = "pear";

2.3 Removing Elements from an Array

To remove an element by its index, use the unset() function:


unset($fruits[0]);

2.4 Merging Arrays

You can combine two or more arrays using the array_merge() function:


$foods = array_merge($fruits, $vegetables);

2.5 Filtering Array Values

To filter out empty values or apply custom logic, use the array_filter() function with a callback:


$filtered_fruits = array_filter($fruits, function($fruit) {
    return $fruit != "";
});

This example removes all empty elements from the array.

3. Conclusion

Arrays in PHP are versatile and essential for managing grouped data. Whether you're looping through elements, modifying the array structure, or applying filters, mastering arrays is fundamental to PHP programming. This guide offers a solid foundation for beginners looking to work efficiently with PHP arrays.