PHP Indexed Arrays 🎯

beginner
12 min

PHP Indexed Arrays 🎯

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.

What is an Array? πŸ“

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.

Why PHP Arrays? πŸ’‘

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.

Creating an Array βœ…

To create an array in PHP, we use square brackets []. Here's a simple example:

php
$colors = array("red", "blue", "green"); echo $colors[0]; // Output: red

In 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.

Accessing and Manipulating Arrays πŸ’‘

To access an array element, we use its index enclosed in square brackets. Here's an example:

php
$colors = array("red", "blue", "green"); echo $colors[1]; // Output: blue

We can also change the value of an array element by assigning a new value to its index:

php
$colors = array("red", "blue", "green"); $colors[1] = "purple"; echo $colors[1]; // Output: purple

Multidimensional Arrays πŸ’‘

A multidimensional array is an array with more than one level of indices. Here's an example:

php
$cars = array( array("brand" => "Toyota", "model" => "Corolla"), array("brand" => "Honda", "model" => "Civic"), array("brand" => "Ford", "model" => "Mustang") ); echo $cars[1]["brand"]; // Output: Honda

In 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.

Looping through Arrays πŸ’‘

To loop through an array, we can use PHP's foreach loop or for loop. Here's an example using foreach:

php
$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.

Quiz πŸ’‘

Quick Quiz
Question 1 of 1

What is an array in PHP?

Quick Quiz
Question 1 of 1

How can we create an array in PHP?

Quick Quiz
Question 1 of 1

How can we access an array element in PHP?