```html Arrays in PHP 8.2 | PHP: Hypertext Preprocessor
PHP

Arrays

PHP 8.2 • Data Storage and Manipulation

Introduction to Arrays

Arrays are ordered maps that can hold scalar values or reference other arrays. PHP supports indexed and associative arrays.

Indexed Arrays

1. Numerical Indexing

<?php
$fruits = ['apple', 'banana', 'cherry'];
foreach ($fruits as $fruit) {
    echo $fruit . "
"; } ?>

Access elements via numeric keys starting from zero.

2. Multi-Dimensional Arrays

<?php
$matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
];
print_r($matrix);
?>

Nested arrays can represent matrices or complex data structures.

Associative Arrays

Key-Value Pairs

<?php
$prices = [
    'apple' => 1.50,
    'banana' => 0.75,
    'cherry' => 2.00
];
echo 'Apple price: $' . $prices['apple'];
?>

Use custom strings as keys for more readable data structures.

Array Functions

1. Built-in Array Tools

<?php
$numbers = [3, 1, 4, 1, 5, 9];
sort($numbers);
print_r($numbers);
?>

2. Array Iteration

<?php
$users = ['Alice', 'Bob', 'Charlie'];
array_map(fn($user) => 'Hello, ' . $user, $users);
?>

Best Practices

Use Type Checks

Verify data types using is_array() when handling user input.

Optimize Memory

Leverage foreach for readability and performance with big arrays.

See Also

array_map()

Functions that process array elements transformations

View details

Array Constants

Creating constants arrays for configuration values

View syntax
Tip: Prefer foreach for array iteration. Use array_map or other functional functions for complex transformations.
```