Welcome to the PHP Indexed Arrays tutorial! In this lesson, we'll learn about one of the fundamental data structures in PHP - Arrays. We'll start from the basics, and gradually move on to more advanced examples. By the end of this lesson, you'll be able to create, manipulate, and utilize indexed arrays in your PHP projects.
An array is a collection of values that can be of different data types, but are stored in a single variable. Each value in an array is called an element, and they are identified by an index.
Arrays are incredibly useful in PHP for handling multiple values efficiently and performing complex operations. They're widely used in real-world projects, from managing user data in a database to organizing shopping cart items in an e-commerce website.
To create an array in PHP, we use square brackets []. Here's a simple example:
$colors = array("red", "blue", "green");
echo $colors[0]; // Output: redIn this example, we've created an array named $colors with three elements: "red", "blue", and "green". We can access each element by its index, which starts at 0.
To access an array element, we use its index enclosed in square brackets. Here's an example:
$colors = array("red", "blue", "green");
echo $colors[1]; // Output: blueWe can also change the value of an array element by assigning a new value to its index:
$colors = array("red", "blue", "green");
$colors[1] = "purple";
echo $colors[1]; // Output: purpleA multidimensional array is an array with more than one level of indices. Here's an example:
$cars = array(
array("brand" => "Toyota", "model" => "Corolla"),
array("brand" => "Honda", "model" => "Civic"),
array("brand" => "Ford", "model" => "Mustang")
);
echo $cars[1]["brand"]; // Output: HondaIn this example, we've created a multidimensional array called $cars. It contains three sub-arrays, each representing a car with its brand and model. We can access the elements of a sub-array using their indices, similar to one-dimensional arrays.
To loop through an array, we can use PHP's foreach loop or for loop. Here's an example using foreach:
$cars = array(
array("brand" => "Toyota", "model" => "Corolla"),
array("brand" => "Honda", "model" => "Civic"),
array("brand" => "Ford", "model" => "Mustang")
);
foreach ($cars as $car) {
echo $car["brand"] . " - " . $car["model"] . "\n";
}In this example, we're looping through the $cars array and printing the brand and model of each car.
What is an array in PHP?
How can we create an array in PHP?
How can we access an array element in PHP?