A Comprehensive Guide to PHP Arrays (With Examples)

By Shahnail Khan Last updated : December 12, 2023

PHP Arrays

Arrays are versatile and powerful data structures that allow you to store and organize multiple values under a single variable name. In this tutorial, we'll cover the basics of PHP arrays, their types, and how to work with them effectively and traverse through their elements.

What is an Array?

An array in PHP is a collection of elements, each identified by a unique key or index. These elements can be of any data type, and arrays provide a convenient way to manage and manipulate related data.

Let's consider a scenario where we want to store the scores of students in a class. Instead of creating individual variables for each student, we can use an array to efficiently manage the data.

Suppose we have the scores of 20 students:

  • Student 1: 85
  • Student 2: 92
  • Student 3: 78
  • ...
  • Student 20: 81

Instead of creating separate variables like $score1, $score2, ..., $score20, we can use a single array to store all the scores:

$scores = array(85, 92, 78, 95, 88, 70, 89, 94, 79, 87, 91, 83, 76, 98, 82, 90, 73, 86, 99, 81);

Now, if we want to print the scores for each student, we can use a loop.

This way, using an array makes it much more convenient to manage and access the scores, especially when dealing with many students. It simplifies the code and avoids the need for numerous individual variables.

Creating an Array in PHP

You can create an array in PHP using the array() function. Here's a simple example:

Example

<?php
$students = array("Alvin", "Alex", "Bob");
?>

In this example, $students is an array containing three elements: "Alvin," "Alex," and "Bob."

Getting Information of PHP Array

To get all the information about a PHP array, you can use the var_dump() function. This function dumps information about one or more variables (PHP array, also).

Example

Create an array and dump its all information.

<?php
// Creating an array
$students = array("Alvin", "Alex", "Bob");

// Printing it's all information
var_dump($students);
?>

The output of the above example is:

array(3) { [0]=> string(5) "Alvin" [1]=> string(4) "Alex" [2]=> string(3) "Bob" }

Accessing PHP Array Elements

To get an element of a PHP array, use the index of the elements within the subscript (square brackets []). Let's suppose if you want to access second elements of a PHP array, use $array_name[1].

Example

Create an array, access and print its elements using the indexes.

<?php
// Creating an array
$students = array("Alvin", "Alex", "Bob");

// Printing elements
echo "Element at 0 index is: $students[0]" . "<br>";
echo "Element at 1 index is: $students[1]" . "<br>";
echo "Element at 2 index is: $students[2]" . "<br>";
?>

The output of the above example is:

Element at 0 index is: Alvin
Element at 1 index is: Alex
Element at 2 index is: Bob

Getting Length of PHP Array

To get the length (total number of elements) of a PHP array, you can use the count() function.

Example

Create an array and print the total number of elements.

<?php
// Creating an array
$students = array("Alvin", "Alex", "Bob");

// Getting total number of elements
$len = count($students);
echo "Total number of elements: $len";
?>

The output of the above example is:

Total number of elements: 3

Types of PHP Arrays

In PHP, there are three main types of arrays:

  1. Indexed Arrays
  2. Associative Arrays
  3. Multidimensional Arrays

1. Indexed Arrays

The most basic type of PHP array is an indexed array. Elements are assigned a numeric index, starting from 0. Let's take an example to understand this array better.

Example

<?php
// Indexed array containing car names
$cars = array("Toyota", "Honda", "Ford", "Chevrolet", "BMW");

// Accessing and displaying array elements using a loop
echo "List of Cars:<br>";
for ($i = 0; $i < count($cars); $i++) {
    echo $i + 1 . ". " . $cars[$i] . "<br>";
}
?>

The output of the above example is:

List of Cars:
1. Toyota
2. Honda
3. Ford
4. Chevrolet
5. BMW

In this example, we have an indexed array $cars that store the names of different car brands. The for loop is used to display each car's name along with its position.

2. Associative Arrays

Associative arrays use named keys instead of numeric indices. Each element is associated with a unique key-value pair. Let's take an example to understand this array better.

Example

<?php
// Associative array representing a person's details
$person = array(
    "name" => "Alvin",
    "age" => 22,
    "city" => "London",
    "occupation" => "Software Engineer",
);

// Accessing and displaying details
echo "Person's Details:<br>";
echo "Name: " . $person["name"] . "<br>";
echo "Age: " . $person["age"] . "<br>";
echo "City: " . $person["city"] . "<br>";
echo "Occupation: " . $person["occupation"] . "<br>";
?>

The output of the above example is:

Person's Details:
Name: Alvin
Age: 22
City: London
Occupation: Software Engineer

In this example, we've used an associative array $person to store details about an individual, such as name, age, city, and occupation. We access and print each detail using the corresponding key.

3. Multidimensional Arrays

PHP arrays can also be multidimensional, meaning they contain other arrays. This is useful for organizing complex data structures. Let's take an example to understand this array better.

Example

<?php
// Multidimensional array representing a matrix
$matrix = array(array(1, 2, 3), array(4, 5, 6), array(7, 8, 9));

// Accessing and displaying elements
echo "Matrix Elements:<br>";
echo $matrix[0][0] . " " . $matrix[0][1] . " " . $matrix[0][2] . "<br>";
echo $matrix[1][0] . " " . $matrix[1][1] . " " . $matrix[1][2] . "<br>";
echo $matrix[2][0] . " " . $matrix[2][1] . " " . $matrix[2][2] . "<br>";
?>

The output of the above example is:

Matrix Elements:
1 2 3
4 5 6
7 8 9

Here, we've created a multidimensional array $matrix to represent a 3x3 matrix. The nested echo statements demonstrate how to access and print individual elements in a two-dimensional array.

Traversing PHP Arrays

Traversing or looping through PHP arrays is essential to access and manipulate their elements.

Example

In this code we have traversed an array using foreach loop.

<?php
$students = array("Alvin", "Alex", "Bob");

echo "Array elements: ";
foreach ($students as $student) {
    echo $student . " ";
}
?>

The output of the above example is:

Array elements: Alvin Alex Bob

In PHP, there are several ways to traverse or iterate through arrays, depending on the type of array and the specific requirements of your code.

Let's have a look at some common methods for traversing arrays in PHP:

Traverse PHP Array Using foreach Loop

<?php
$students = array("Alvin", "Alex", "Bob");

echo "Array elements: ";
foreach ($students as $student) {
    echo $student . " ";
}

// Output: Array elements: Alvin Alex Bob
?>

In this example, the foreach loop is used to iterate through the $students array. For each iteration, the current fruit is assigned to the variable $student, which is then displayed.

Traverse PHP Array Using for Loop with Count

<?php
$students = array("Alvin", "Alex", "Bob");

echo "Array elements: ";
for ($i = 0; $i < count($students); $i++) {
    echo $students[$i] . " ";
}

// Output: Array elements: Alvin Alex Bob
?>

Here, a for loop is used to iterate through the $students array. The loop runs until the index $i reaches the count of elements in the array. The elements are then printed one by one.

Traverse PHP Array Using while Loop

<?php
$students = array("Alvin", "Alex", "Bob");
$index = 0;

echo "Array elements: ";
while ($index < count($students)) {
    echo $students[$index] . " ";
    $index++;
}

// Output: Array elements: Alvin Alex Bob
?>

In this example, a while loop is used to traverse through the $students array. The loop continues as long as the $index is less than the count of elements in the array. The elements are printed, and the index is incremented in each iteration.

Mixed int and string keys in PHP Array

In a PHP array, you can use mixed types of keys (int, string), array can be created and accessed through these keys.

Example

Create an array with mixed int and string keys and print its all information.

<?php
$car = array(
    "company" => "Honda",
    "model" => "City New",
    101 => 2022,
    102 => 180,
);

// Dumping array information
echo "Array information:" . "<br>";
var_dump($car);
echo "<br><br>";

// Accessing and printing each element through key
echo "Array elements:" . "<br>";
echo "Value with 'company' key: $car[company]" . "<br>";
echo "Value with 'mode' key: $car[model]" . "<br>";
echo "Value with '101' key: $car[101]" . "<br>";
echo "Value with '102' key: $car[102]" . "<br>";
?>

The output of the above example is:

Array information:
array(4) { ["company"]=> string(5) "Honda" ["model"]=> string(8) "City New" [101]=> int(2022) [102]=> int(180) }

Array elements:
Value with 'company' key: Honda
Value with 'mode' key: City New
Value with '101' key: 2022
Value with '102' key: 180

Keys not on all Elements in PHP Array

It is possible to create an array with a few keys. If you create an array without keys and assign a few keys, in that case, automatic keys will be assigned (starting with 0).

Example

Create an array where keys are not on all elements.

<?php
$arr = array(
	"abc",
    "pqr",
10 => "xyz",
    "mno"
);

// Dumping array information
echo "Array information:" . "<br>";
var_dump($arr);
?>

The output of the above example is:

Array information:
array(4) { [0]=> string(3) "abc" [1]=> string(3) "pqr" [10]=> string(3) "xyz" [11]=> string(3) "mno" }

Useful Resources


Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.