PHP Array
An array is a special variable that can hold multiple values at the same time. In PHP, we can work with arrays via various built-in functions and operators.
Syntax
To define an array, use the following syntax:
$variable_name = array(value1, value2, value3, ...);
Or, in the case of PHP 5.4+, we can use the shorthand array syntax:
$variable_name = [value1, value2, value3, ...];
Example
$fruits = array("apple", "banana", "orange");
$numbers = [1, 2, 3, 4, 5];
Output
To output an array, we can use the print_r()
function which displays human-readable information about a variable:
print_r($fruits);
Output:
Array
(
[0] => apple
[1] => banana
[2] => orange
)
Explanation
An array can hold any type of data including strings, integers, floats, booleans, objects, and even other arrays. The values inside an array are assigned an index starting from 0 by default.
We can access individual elements of arrays by their index:
echo $fruits[0]; // output: apple
We can also iterate through an array using a loop:
foreach ($fruits as $fruit) {
echo $fruit . " ";
}
// output: apple banana orange
Use
Arrays are often used to store and manipulate large sets of data efficiently. They can be used to keep track of information about products, users, posts, etc.
Arrays also have built-in functions like count()
, sort()
, array_merge()
, array_slice()
, etc. that can help us perform various operations on arrays.
Important Points
- An array is a special variable that can hold multiple values at the same time.
- We can access the elements of an array using their index.
- We can iterate through an array using a loop.
- Arrays can store any type of data and can even contain other arrays as elements.
- PHP has many built-in functions that can be used with arrays.
Summary
In this tutorial, we learned how to define and use arrays in PHP. We also explored various built-in functions and operators that are available to manipulate arrays in PHP. By learning arrays, we can handle large sets of data efficiently and effectively.