Arrays are a fundamental data structure in PHP, allowing you to store and manipulate collections of data. In this lesson, we will explore creating and working with arrays, as well as using built-in array functions in PHP.
There are two types of arrays in PHP: indexed arrays and associative arrays.
$fruits = array("apple", "banana", "cherry");
$person = array("name" => "John", "age" => 30, "city" => "New York");
You can perform various operations on arrays, such as adding elements, accessing elements, and looping through arrays.
$fruits[] = "orange"; // Adds "orange" to the end of the array
echo $fruits[0]; // Output: apple
echo $person["name"]; // Output: John
phpCopy code
foreach ($fruits as $fruit) {
echo $fruit . "<br>";
}
foreach ($person as $key => $value) {
echo "$key: $value<br>";
}
PHP provides numerous built-in functions for working with arrays:
count()
: Returns the number of elements in an array.$num_fruits = count($fruits);
sort()
and rsort()
: Sort an array in ascending or descending order.