How to use a PHP array

PHP arrays efficiently group, manage, and retrieve data using a single identifier. Their dynamic resizing feature enables flexible element addition or removal based on your needs. Consequently, arrays prove to be an essential tool in PHP programming.

What is a PHP array?

A PHP array can hold different types of data, such as numbers, strings, booleans and more. They organize these values in an ordered and hierarchical 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-dimensional organization.

In combination with arrays, PHP classes provide even more structure. A class can be a collection of functions specifically designed for manipulating arrays. Examples include filtering data, adding or deleting elements, or even calculating statistical values. This object-oriented concept increases code organization and maintainability.

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 definition has been introduced, making the use of the array() function optional.

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

This shortened form in square brackets allows a more compact representation of arrays and is often found to be more readable.

For a detailed introduction to PHP programming, we recommend our PHP tutorial. Check out comparisons between PHP vs. Python and PHP vs. JavaScript 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) represents a numeric array that can be accessed via $numArray[2] to get the value 30.

Associative arrays, on the other hand, are distinguished by user-defined keys for accessing values. A PHP array with associative properties 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”. Associative arrays are particularly useful for storing data with meaningful labels.

For more complex structures, multidimensional 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 management
  • Easy SSL admin
  • API documentation

Examples for the use of arrays in PHP

Addition of numeric values

Arithmetic PHP operators allow you to process numeric arrays, for example by adding values and calculating 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 information 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 associative array with the keys “name” and “age.” The output will present the retrieved data in the structure of the $userArray.

IONOS Object Storage
Secure, affordable storage

Cost-effective, scalable storage that integrates into your application scenarios. Protect your data with highly secure servers and individual access control.

Was this article helpful?
We use cookies on our website to provide you with the best possible user experience. By continuing to use our website or services, you agree to their use. More Information.
Page top