How can developers optimize their code when working with arrays in PHP to avoid inefficiencies or errors?

When working with arrays in PHP, developers can optimize their code by using built-in array functions instead of manually iterating through arrays. This can help avoid inefficiencies and errors by leveraging the optimized code provided by PHP. Additionally, developers should consider using associative arrays when key-value pairs are needed, as they can provide faster lookups compared to indexed arrays.

// Example of optimizing code when working with arrays in PHP

// Using array_map to apply a callback function to each element of an array
$numbers = [1, 2, 3, 4, 5];
$squaredNumbers = array_map(function($num) {
    return $num * $num;
}, $numbers);

print_r($squaredNumbers);

// Using associative arrays for key-value pairs
$user = [
    'name' => 'John Doe',
    'age' => 30,
    'email' => 'john.doe@example.com'
];

echo $user['name'];