What are the potential pitfalls of using a while loop to output categories and subcategories in PHP?
The potential pitfall of using a while loop to output categories and subcategories in PHP is that it can lead to infinite looping if not implemented correctly. To avoid this issue, it is important to ensure that the loop has a proper exit condition to prevent it from running indefinitely.
// Sample code to output categories and subcategories using a recursive function
function outputCategories($categories, $parent_id = 0, $level = 0) {
foreach ($categories as $category) {
if ($category['parent_id'] == $parent_id) {
echo str_repeat('-', $level) . $category['name'] . "\n";
outputCategories($categories, $category['id'], $level + 1);
}
}
}
// Example usage
$categories = [
['id' => 1, 'name' => 'Category 1', 'parent_id' => 0],
['id' => 2, 'name' => 'Subcategory 1-1', 'parent_id' => 1],
['id' => 3, 'name' => 'Subcategory 1-2', 'parent_id' => 1],
['id' => 4, 'name' => 'Category 2', 'parent_id' => 0],
['id' => 5, 'name' => 'Subcategory 2-1', 'parent_id' => 4],
];
outputCategories($categories);