0

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

Community
  • 1
  • 1
Jesse Elser
  • 974
  • 2
  • 11
  • 39
  • Because `$_SERVER["REQUEST_URI"]` starts with a `/` so you always get a minimum of two array elements when exploding. Try this: `explode("/", trim($_SERVER["REQUEST_URI"], '/'));` – M. Eriksson Oct 11 '16 at 05:45

1 Answers1

3

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;
   }
amow
  • 2,203
  • 11
  • 19