PHP arrays ef­fi­ciently group, manage, and retrieve data using a single iden­ti­fi­er. Their dynamic resizing feature enables flexible element addition or removal based on your needs. Con­sequently, arrays prove to be an essential tool in PHP pro­gram­ming.

What is a PHP array?

A PHP array can hold different types of data, such as numbers, strings, booleans and more. They organise these values in an ordered and hier­arch­ic­al structure, serving a wide range of purposes. Arrays are valuable not only for basic tasks like storing lists of items but also for complex scenarios where data requires multi-di­men­sion­al or­gan­isa­tion.

In com­bin­a­tion with arrays, PHP classes provide even more structure. A class can be a col­lec­tion of functions spe­cific­ally designed for ma­nip­u­lat­ing arrays. Examples include filtering data, adding or deleting elements, or even cal­cu­lat­ing stat­ist­ic­al values. This object-oriented concept increases code or­gan­isa­tion and main­tain­ab­il­ity.

Tip

With Deploy Now from IONOS you can deploy your own website directly via GitHub. Benefit from an easy setup and flexible, scalable resources.

Syntax of arrays in PHP

In PHP there are two ways to define arrays:

The array() function

The array() function is one of the built-in PHP functions and is used to define and create a PHP array. It takes one or more values as arguments and returns an array. The syntax looks like this:

$numArray = array(10, 20, 30, 40);
php

This creates a numeric array with the values 10, 20, 30 and 40.

Short form

As of PHP version 5.4, a shorter syntax for the array defin­i­tion has been in­tro­duced, making the use of the array() function optional.

$numArray = [10, 20, 30, 40];
php

This shortened form in square brackets allows a more compact rep­res­ent­a­tion of arrays and is often found to be more readable.

For a detailed in­tro­duc­tion to PHP pro­gram­ming, we recommend our PHP tutorial. Check out com­par­is­ons between PHP vs Python and PHP vs JavaS­cript in the Digital Guide.

What types of PHP arrays are there?

Numeric arrays are the simplest form of arrays and use ascending integers as indices. The stored values are accessed using these indices. For example, $numArray = array(10, 20, 30, 40) rep­res­ents a numeric array that can be accessed via $numArray[2] to get the value 30.

As­so­ci­at­ive arrays, on the other hand, are dis­tin­guished by user-defined keys for accessing values. A PHP array with as­so­ci­at­ive prop­er­ties might look like the following:

$assocArray = array("Name" => "John", "Age" => 25, "City" => "New York")
php

Here, the key ‘name’ provides access to the value ‘John’. As­so­ci­at­ive arrays are par­tic­u­larly useful for storing data with mean­ing­ful labels.

For more complex struc­tures, mul­ti­di­men­sion­al arrays provide a solution. These arrays contain other arrays as elements:

$multiDimArray = array(
    array(1, 2, 3),
    array(4, 5, 6),
    array(7, 8, 9)
);
php
IONOS Developer API
Manage your hosting products through our powerful API
  • DNS man­age­ment
  • Easy SSL admin
  • API doc­u­ment­a­tion

Examples for the use of arrays in PHP

Addition of numeric values

Arith­met­ic PHP operators allow you to process numeric arrays, for example by adding values and cal­cu­lat­ing the sum:

// Numeric array
$numArray = [10, 20, 30, 40, 50];
// Calculate sum
$sum = 0;
foreach ($numArray as $value) {
    $sum += $value;
}
echo "Sum: " . $sum . "<br>";
php

Output the number of elements in a PHP array

Use the count() function to determine the PHP array length:

$cars = array("Volvo", "BMW", "Toyota");
echo count($cars);
php

PHP database query

You can also use PHP to retrieve in­form­a­tion from a MySQL database.

// Retrieve data from the database and store it in an array
$sql = "SELECT Name, Age OF User";
$result = $conn->query($sql);
$userArray = [];
if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        $userArray[] = [
            "Name" => $row["Name"],
            "Age" => $row["Age"]
        ];
    }
}
// Close database connection
$conn->close();
// Array output
print_r($userArray);
php

In this example, we execute a SQL query to fetch the names and ages of users and store the retrieved data in a PHP array named $userArray. Each element in the array comprises an as­so­ci­at­ive array with the keys ‘name’ and ‘age’. The output will present the retrieved data in the structure of the $userArray.

IONOS Cloud Object Storage
Cloud storage at an un­beat­able price

Cost-effective, scalable storage that in­teg­rates into your ap­plic­a­tion scenarios. Protect your data with highly secure servers and in­di­vidu­al access control.

Go to Main Menu