How can nested loops be optimized for performance when working with arrays in PHP?

Nested loops can be optimized for performance when working with arrays in PHP by minimizing the number of iterations and reducing unnecessary operations within the loops. One way to do this is by using associative arrays or multidimensional arrays to store and access data more efficiently. Additionally, consider using built-in array functions like array_map, array_filter, or array_reduce to perform operations on arrays without the need for nested loops.

// Example of optimizing nested loops with associative arrays
$data = [
    ['id' => 1, 'name' => 'Alice'],
    ['id' => 2, 'name' => 'Bob'],
    ['id' => 3, 'name' => 'Charlie']
];

// Using associative arrays to access data more efficiently
$indexedData = [];
foreach ($data as $item) {
    $indexedData[$item['id']] = $item;
}

// Accessing data without nested loops
echo $indexedData[2]['name']; // Output: Bob