How to make dynamic breadcrum using segments

// This function will take $_SERVER['REQUEST_URI'] and build a breadcrumb based on the user's current path

function getBreadcrumbs($separator = ' &raquo; ', $home = 'Home') {

// This gets the REQUEST_URI (/path/to/file.php), splits the string (using '/') into an array,

$current_segments = explode('/', parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH));

//filters out any empty value

$path = array_filter($current_segments);

 // This will build our "base URL" ... Also accounts for HTTPS :)

$base = 'http://'.$_SERVER['HTTP_HOST'].'/';

     // Initialize breadcrumbs.(starting with our home page)

    $breadcrumbs = Array("<a href=\"$base\">$home</a>");

// Find out the index for the last value in our path array

 $array_keys = (array_keys($path));

 $last = end($array_keys);

// Build the rest of the breadcrumbs

    foreach ($path AS $x => $crumb) {

        // Our "title" is the text that will be displayed (strip out .php and turn '_' into a space)

        $title = ucwords(str_replace(Array('.php', '_'), Array('', ' '), $crumb));

        // If not on the last index,display an <a> tag

        if ($x != $last)

            $breadcrumbs[] = "<a href=\"$base$crumb\">$title</a>";

        // Otherwise, display the title


            $breadcrumbs[] = $title;

    // Build array (pieces of bread) into one big string

    return implode($separator, $breadcrumbs);



<p><?= getBreadcrumbs(' > ') ?></p>
Please follow and like us: