In what situations is it recommended to work directly with a database instead of using PHP arrays for data manipulation?

When dealing with large datasets or when data needs to be persisted across different sessions or users, it is recommended to work directly with a database instead of using PHP arrays for data manipulation. Databases provide efficient storage, querying, and indexing capabilities that can handle large amounts of data more effectively than PHP arrays. Additionally, databases offer features like transactions, data integrity constraints, and scalability that are essential for managing complex data relationships and ensuring data consistency.

// Connect to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

$conn = new mysqli($servername, $username, $password, $dbname);

// Perform database operations
$sql = "SELECT * FROM users";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // Output data of each row
    while($row = $result->fetch_assoc()) {
        echo "id: " . $row["id"]. " - Name: " . $row["name"]. "<br>";
    }
} else {
    echo "0 results";
}

// Close the database connection
$conn->close();