Arrays in PHP
Arrays are used to store multiple values in a single variable. PHP supports several types of arrays, allowing you to organize and manage data effectively.
Indexed Arrays
Indexed arrays use numeric indices to access values. They are the simplest type of arrays.
- Creating an Indexed Array:
$fruits = array("Apple", "Banana", "Cherry");
- Accessing Values:
echo $fruits[0]; // Outputs: Apple
- Adding Values:
$fruits[] = "Date"; // Adds "Date" to the end of the array
Associative Arrays
Associative arrays use named keys to access values, providing a way to store data in a key-value pair format.
- Creating an Associative Array:
$person = array(
"first_name" => "John",
"last_name" => "Doe",
"age" => 30
);
- Accessing Values:
echo $person["first_name"]; // Outputs: John
- Adding Values:
$person["email"] = "[email protected]";
Multidimensional Arrays
Multidimensional arrays are arrays containing other arrays. They are useful for storing more complex data structures.
- Creating a Multidimensional Array:
$contacts = array(
array("John Doe", "[email protected]"),
array("Jane Smith", "[email protected]")
);
- Accessing Values:
echo $contacts[0][0]; // Outputs: John Doe
- Adding Values:
$contacts[] = array("Mike Johnson", "[email protected]");
Array Functions
PHP provides a wide range of built-in functions for working with arrays.
-
Array Functions:
array_push()
: Adds one or more elements to the end of an array.
array_push($fruits, "Elderberry");
array_pop()
: Removes the last element from an array.
$lastFruit = array_pop($fruits);
array_shift()
: Removes the first element from an array.
$firstFruit = array_shift($fruits);
array_unshift()
: Adds one or more elements to the beginning of an array.
array_unshift($fruits, "Apricot");
array_merge()
: Merges two or more arrays into one.
$moreFruits = array("Fig", "Grape"); $allFruits = array_merge($fruits, $moreFruits);
count()
: Counts all elements in an array.
$numFruits = count($fruits);
in_array()
: Checks if a value exists in an array.
$hasBanana = in_array("Banana", $fruits);
array_keys()
: Returns all the keys of an array.
$keys = array_keys($person);
array_values()
: Returns all the values of an array.
$values = array_values($person);
Arrays are a powerful feature in PHP, enabling you to manage and manipulate sets of data efficiently. Understanding the different types of arrays and their associated functions will help you handle various data structures in your PHP applications.