What are the potential pitfalls of using multiple arrays in PHP for templating purposes?
Using multiple arrays for templating purposes can lead to confusion and make the code harder to maintain. It can also result in inefficient code as it requires iterating through multiple arrays to retrieve the necessary data. To solve this issue, consider using a single multidimensional array to store all the necessary data for the template.
// Example of using a single multidimensional array for templating
$data = [
'user' => [
'name' => 'John Doe',
'email' => 'john.doe@example.com',
],
'products' => [
['name' => 'Product 1', 'price' => 10],
['name' => 'Product 2', 'price' => 20],
],
];
// Accessing data in the template
echo "Welcome, " . $data['user']['name'] . "!";
foreach ($data['products'] as $product) {
echo $product['name'] . ": $" . $product['price'] . "<br>";
}