Arrays are fundamental data structures that allow you to store multiple values under a single variable name.
Creating Arrays:
[] or the array() function.$numbers = [1, 2, 3, 4, 5];
$fruits = array("Apple", "Banana", "Orange");
Accessing Elements:
echo $numbers[0]; // Outputs: 1
echo $fruits[2]; // Outputs: Orange
Adding Elements:
array_push() function.$numbers[] = 6; // Adds 6 to the end of $numbers
array_push($fruits, "Kiwi"); // Adds "Kiwi" to the end of $fruits
Removing Elements:
unset() or specific functions like array_pop() or array_shift().unset($numbers[3]); // Removes element at index 3
array_pop($fruits); // Removes the last element from $fruits
array_shift($numbers); // Removes the first element from $numbers
Array Length:
count() function.echo count($numbers); // Outputs: 5
Iterating Through Arrays:
foreach or traditional for loops to iterate through arrays.foreach ($fruits as $fruit) {
echo $fruit . "<br>";
}
Array Functions:
sort(), rsort(): Sorts an array in ascending or descending order.array_filter(): Filters elements of an array using a callback function.array_merge(): Merges one or more arrays.array_search(): Searches an array for a given value and returns the corresponding key if successful.array_key_exists(): Checks if the given key or index exists in the array.array_slice(): Extracts a slice of an array.Multi-dimensional Arrays:
$matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
Understanding these array operations and functions in PHP will empower you to write cleaner, more efficient, and maintainable code. Arrays are powerful tools for managing data structures, and mastering their usage is essential for proficient PHP development.