Jesse Elser Jesse Elser - 1 month ago 20
PHP Question

PHP Breadcrumb Generates Empty Link

I'm using this simple code to generate breadcrumbs:

<ul class="breadcrumb">
<?php
$crumbs = explode("/",$_SERVER["REQUEST_URI"]);
foreach($crumbs as $crumb){
echo ' <li>';
echo '<a href="'.$crumb.'">';
echo ucfirst(str_replace(array(".php","_"),array(""," "),$crumb) . '');
echo '</a>';
echo '<span class="divider">/</span></li>' . PHP_EOL;
}
?>
</ul>


Right now my URL is
http://example.com/gallery.php
.

For some reason this script is generating an empty anchor tag and an anchor tag for
gallery.php
.

Could anyone tell me why an empty anchor tag is being generated?

The actual output is:

<ul class="breadcrumb">
<li><a href=""></a><span class="divider">/</span></li>
<li><a href="gallery.php">Gallery</a><span class="divider">/</span></li>
</ul>


I got this example from: PHP Simple dynamic breadcrumb

Answer

Because explode("/", "/asd/ddd") returns ["", "asd", "ddd"]

Add an if statement will work.

foreach($crumbs as $crumb){
    if(!$crumb) continue;
    echo '   <li>';
    echo '<a href="'.$crumb.'">';
    echo ucfirst(str_replace(array(".php","_"),array(""," "),$crumb) . '');
    echo '</a>';
    echo '<span class="divider">/</span></li>' . PHP_EOL;
   }
Comments