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.
There are two primary ways to define an array in PHP:
$fruits = array("apple", "orange", "banana");
Or using the modern syntax:
$fruits = ["apple", "orange", "banana"];
You can access elements in an array using their index. Array indexes start from 0:
echo $fruits[0]; // Outputs "apple"
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
You can add new elements to the end of an array using the following syntax:
$fruits[] = "pear";
To remove an element by its index, use the unset() function:
unset($fruits[0]);
You can combine two or more arrays using the array_merge() function:
$foods = array_merge($fruits, $vegetables);
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.
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.