What are common pitfalls when working with arrays in PHP, especially when fetching data from a database?

One common pitfall when working with arrays in PHP, especially when fetching data from a database, is not properly handling empty results. It's important to check if the array is empty before trying to access its elements to avoid errors. Another common issue is not sanitizing input data when building arrays, which can lead to security vulnerabilities. Additionally, be mindful of the data types stored in the array to prevent unexpected behavior.

// Example of properly handling empty results when fetching data from a database
$result = $db->query("SELECT * FROM users WHERE id = $user_id");
if ($result && $result->num_rows > 0) {
    $user_data = $result->fetch_assoc();
    // Process user data
} else {
    echo "No user found with that ID";
}