What are the best practices for creating breadcrumb navigation in PHP?

Creating breadcrumb navigation in PHP involves storing the hierarchical structure of the website pages and dynamically generating the breadcrumb trail based on the current page being viewed. This can be achieved by using an array to store the page hierarchy and then iterating through the array to build the breadcrumb trail. By implementing this approach, users can easily navigate back to previous pages within the website.

<?php
// Define the page hierarchy as an associative array
$pages = array(
    'Home' => 'index.php',
    'Products' => 'products.php',
    'Category 1' => 'category1.php',
    'Category 2' => 'category2.php',
    'Product A' => 'productA.php',
    'Product B' => 'productB.php'
);

// Get the current page URL
$current_page = basename($_SERVER['PHP_SELF']);

// Generate breadcrumb navigation
$breadcrumbs = array();
foreach ($pages as $page => $url) {
    if ($url == $current_page) {
        $breadcrumbs[] = '<a href="' . $url . '">' . $page . '</a>';
        break;
    } else {
        $breadcrumbs[] = '<a href="' . $url . '">' . $page . '</a>';
    }
}

// Output breadcrumb trail
echo implode(' > ', $breadcrumbs);
?>