views:

192

answers:

4

I'm pulling the url parameter and I'm trying to create a breadcrumb out of it. So, if I pull:

$url = 'contact/jane/now';

and I do:

$path = explode("/",$url);

How can I put it in a loop so that it breaks each part into a path like this:

<a href="/contact">contact</a>
<a href="/contact/jane">jane</a>
<a href="/contact/jane/now">now</a>
A: 

You can use a For, For Each, Do, Do While, While. Really whatever you want. http://php.net/manual/en/control-structures.for.php When your explode it turns it into an array of strings http://us.php.net/manual/en/function.explode.php

So, just use the count() method and determine how many elements are in the array http://us.php.net/manual/en/function.count.php

And then go ahead and loop through and read one at a time. If you want to start at the last and then go backwards you simply change your loop to go initialize at the count of the array then subtract one each time from your counter. Otherwise, just do it as normal.

Yay for looking on the PHP doc!

David
A: 

You could use array_slice for that the code is not really tested but I hope you get the idea

...
$url   = explode('/', $url);
$links = array();

for ($i = 0; $i < count($url); $i++) {
    $crumb    = ($i > 0) ? implode('/', array_slice($url, 0, $i)) .'/' : $url[$i] .'/';
    $links[]  = sprintf('<a href="%s">%s</a>', $crumb . $url[$i], $url[$i]);
}
tDo
+4  A: 
$answer = '';
foreach ($path as $path_part){
 $answer .= '/'.$path_part;
 print('<a href="'.$answer.'">'.$path_part.'</a>');
}
Mike Sherov
+1 Simple, clear, direct.
cletus
I would use `"/$path_part"` instead of `'/'.$path_part;`. Same for the print. I think it increases readability.
LiraNuna
I prefer to use single quotes as it makes you separate your string literals from your variables. To me, that is clearer. I also prefer single quotes for speed. To each his/her own, I guess.
Mike Sherov
See... That's why I love this site... I was *so* overthinking it, I'm completely embarrassed and will now go to bed....Thanks! :)
phpN00b
+2  A: 

Pre PHP 5.3:

array_reduce($path, create_function('$a, $b', '
    echo "<a href=\"$a/$b\">$b</a>\n";

    return "$a/$b";
'));

In PHP 5.3:

array_reduce($path, function($a, $b) {
    echo "<a href=\"$a/$b\">$b</a>\n";

    return "$a/$b";
});
LiraNuna
I like this answer. Good example of array_reduce().
Mike Sherov