What are best practices for efficiently working with arrays in PHP, especially when dealing with complex data structures?

When working with arrays in PHP, especially when dealing with complex data structures, it is important to use efficient methods to manipulate and access array elements. One way to improve efficiency is by using built-in array functions like array_map, array_filter, and array_reduce instead of manually iterating over arrays. Additionally, using associative arrays can help organize and access data more effectively.

// Example of efficiently working with arrays in PHP

// Creating a complex data structure using associative arrays
$data = [
    'user1' => [
        'name' => 'John Doe',
        'age' => 30,
        'email' => 'john@example.com'
    ],
    'user2' => [
        'name' => 'Jane Smith',
        'age' => 25,
        'email' => 'jane@example.com'
    ]
];

// Using array_map to capitalize the names of users
$capitalizedNames = array_map(function($user) {
    $user['name'] = strtoupper($user['name']);
    return $user;
}, $data);

// Using array_filter to get users under 30 years old
$under30 = array_filter($data, function($user) {
    return $user['age'] < 30;
});

// Using array_reduce to calculate the average age of users
$totalAge = array_reduce($data, function($carry, $user) {
    return $carry + $user['age'];
}, 0);
$averageAge = $totalAge / count($data);