When working with arrays in PHP, what are some common pitfalls to avoid?

One common pitfall when working with arrays in PHP is not properly checking if an array key exists before accessing it. This can lead to errors if the key does not exist, causing your code to break. To avoid this issue, always use array_key_exists() or isset() to check if a key exists before trying to access it.

// Incorrect way of accessing array key without checking
$array = ['key' => 'value'];
echo $array['non_existent_key']; // This will throw an error

// Correct way of checking if array key exists before accessing
$array = ['key' => 'value'];
if (array_key_exists('non_existent_key', $array)) {
    echo $array['non_existent_key'];
} else {
    echo 'Key does not exist';
}