# 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 organise 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 organisation.

In combination with arrays, [PHP classes](https://www.ionos.co.uk/digitalguide/websites/web-development/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 organisation and maintainability.

Tip With [Deploy Now](https://www.ionos.co.uk/hosting/deploy-now "Deploy Now – Websites and Apps via GitHub from IONOS") 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](https://www.ionos.co.uk/digitalguide/websites/web-development/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:

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

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.

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

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](https://www.ionos.co.uk/digitalguide/websites/website-creation/learn-php-our-all-encompassing-php-tutorial-for-beginners/). Check out comparisons between [PHP vs Python](https://www.ionos.co.uk/digitalguide/websites/web-development/php-vs-python/) and [PHP vs JavaScript](https://www.ionos.co.uk/digitalguide/websites/web-development/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:

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

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:

```php
$multiDimArray = array(
    array(1, 2, 3),
    array(4, 5, 6),
    array(7, 8, 9)
);
```

## Examples for the use of arrays in PHP

### Addition of numeric values

Arithmetic [PHP operators](https://www.ionos.co.uk/digitalguide/websites/web-development/php-operators/) allow you to process **numeric arrays**, for example by adding values and calculating the sum:

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

### Output the number of elements in a PHP array

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

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

### PHP database query

You can also [use PHP to retrieve information from a MySQL database](https://www.ionos.co.uk/digitalguide/websites/web-development/use-php-to-retrieve-information-from-a-mysql-mariadb-database/).

```php
// 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);
```

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.


This is a markdown version of: [https://www.ionos.co.uk/digitalguide/websites/web-development/php-arrays/](https://www.ionos.co.uk/digitalguide/websites/web-development/php-arrays/) for AI/LLM consumption.