[php] Best way of finding current page?

Soldato
Joined
18 Oct 2002
Posts
9,044
Location
London
What's the best way of getting id="current" into the <li> for the page the user is currently on? It's only for a tiny site, example:

Code:
<ul>
	<li id="current"><a href="/index.php">Home</a></li>
	<li><a href="/managers.php">Managers</a></li>
	<li><a href="/suppliers.php">Suppliers</a></li>
	<li><a href="/employees.php">Employees</a></li>
	<li><a href="/customers.php">Customers</a></li>
	<li><a href="/stores.php">Stores</a></li>
	<li><a href="/films.php">Films</a></li>
	<li><a href="/genres.php">Genres</a></li>
</ul>


I was thinking

Code:
  if ($scriptname == "/managers.php") {
    <li id="current"><a href="managers.php">Managers</a></li>
  } else {
    <li><a href="/managers.php">Managers</a></li>
  }

But this seems like a lot of lines, and doesn't look very nice.
There must be a better way??? :o
 
You could use the shorthand/ternary operator:
Code:
<li<?php echo ($scriptname == "/managers.php") ? ' id="current"' : '';?>><a href="managers.php">Managers</a></li>;
or store the link items in an array, and output them by looping through the array, template-style. Something like:

Code:
$items = array('Managers' => '/managers.php',
...
)

echo '<ul>';
foreach ($items as $linktext => $link) {
   echo '<li';
   echo ($scriptname == $linktext) ? ' id="current"' : '';
   echo "><a href="$link">$linktext</a></li>";
}
echo '</ul>';
 
Ahhh many thanks, used your 2nd example, very good :)

Never seen this before, although I'm no expert php coder anyway..
Code:
($scriptname == "/managers.php") ? ' id="current"' : '';

Cheers!
 
Also, using ternary operators for anything but the most simply of evaluations/output will make you hated by everyone, FYI.

Good:

Code:
echo "$num post" . ( ( $num == 1 ) ? '' : 's' );

Bad:

Code:
echo ( some_complex_expression(intval(floor($foo))) ) ?
    "
        <div id="foo">
            <p>HELLO</p>
        </div>
    " :
    " 
        <div id="lol">
            <p>KK</p>
        </div>
    ";
 
Last edited:
Back
Top Bottom