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.

Creating Arrays

There are two types of arrays in PHP: indexed arrays and associative arrays.

  1. Indexed arrays: Arrays with numeric keys.
$fruits = array("apple", "banana", "cherry");
  1. Associative arrays: Arrays with string keys.
$person = array("name" => "John", "age" => 30, "city" => "New York");

Array Operations

You can perform various operations on arrays, such as adding elements, accessing elements, and looping through arrays.

  1. Adding elements to an array:
$fruits[] = "orange"; // Adds "orange" to the end of the array
  1. Accessing elements in an array:
echo $fruits[0]; // Output: apple
echo $person["name"]; // Output: John
  1. Looping through an array:
phpCopy code
foreach ($fruits as $fruit) {
  echo $fruit . "<br>";
}

foreach ($person as $key => $value) {
  echo "$key: $value<br>";
}

Array Functions

PHP provides numerous built-in functions for working with arrays:

  1. count(): Returns the number of elements in an array.
$num_fruits = count($fruits);
  1. sort() and rsort(): Sort an array in ascending or descending order.