What are the best practices for handling arrays in PHP when fetching data from a database?

When fetching data from a database in PHP and storing it in an array, it is important to handle the data properly to avoid any unexpected errors or security vulnerabilities. One best practice is to use prepared statements to prevent SQL injection attacks. Additionally, it is recommended to sanitize and validate the data before storing it in the array to ensure its integrity. Lastly, consider using associative arrays to make it easier to access and manipulate the data.

// Example of fetching data from a database and storing it in an array using prepared statements

// Establish a database connection
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");

// Prepare a SQL query
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = :id");

// Bind parameters
$id = 1;
$stmt->bindParam(':id', $id, PDO::PARAM_INT);

// Execute the query
$stmt->execute();

// Fetch data and store it in an associative array
$user = $stmt->fetch(PDO::FETCH_ASSOC);

// Output the user data
print_r($user);