How can indentation be achieved for subcategories in a hierarchical category structure in PHP?

To achieve indentation for subcategories in a hierarchical category structure in PHP, you can use recursion to iterate through the categories and add appropriate indentation based on the depth of each category.

function printCategories($categories, $depth = 0) {
    foreach ($categories as $category) {
        echo str_repeat(' ', $depth * 4) . $category['name'] . "<br>";
        if (!empty($category['subcategories'])) {
            printCategories($category['subcategories'], $depth + 1);
        }
    }
}

// Example usage
$categories = [
    ['name' => 'Category 1', 'subcategories' => [
        ['name' => 'Subcategory 1'],
        ['name' => 'Subcategory 2', 'subcategories' => [
            ['name' => 'Sub-subcategory 1']
        ]]
    ]],
    ['name' => 'Category 2']
];

printCategories($categories);