PHP Arrays
PHP arrays are a fundamental data structure used for storing and managing multiple values in a single variable. They are versatile and allow you to store various types of data, such as numbers, strings, or even other arrays. PHP arrays can be indexed numerically or associatively.
Here’s an example of a numerically indexed array in PHP:
php
$fruits = array("apple", "banana", "orange");
In this case, the array $fruits
contains three elements: “apple” at index 0, “banana” at index 1, and “orange” at index 2. You can access these elements using their respective indices:
php
echo $fruits[0]; // Output: apple
echo $fruits[1]; // Output: banana
echo $fruits[2]; // Output: orange
PHP arrays can also be indexed associatively using strings as keys. Here’s an example:
php
$student = array(
"name" => "John Doe",
"age" => 20,
"major" => "Computer Science"
);
In this case, the array $student
has three elements with string keys: “name”, “age”, and “major”. You can access these elements using their keys:
php
echo $student["name"]; // Output: John Doe
echo $student["age"]; // Output: 20
echo $student["major"]; // Output: Computer Science
PHP arrays offer various functions and methods for manipulating and working with array data. Some common array functions include count()
, array_push()
, array_pop()
, array_merge()
, array_slice()
, and many more.
Additionally, PHP provides control structures like foreach
to iterate over array elements conveniently:
php
foreach ($fruits as $fruit) {
echo $fruit . " ";
}
// Output: apple banana orange
PHP arrays are incredibly versatile and provide a powerful way to handle collections of data efficiently.