The simple answer is that you could use
$_SERVER['SCRIPT_NAME']
instead of
$_SERVER['REQUEST_URI']
The longer answer is that you handle multiple things from your function and this will prevent you from reusing your code.
Please consult the following suggestion:
<?php
/**
* checks if the user called a certain script
*/
function requestMatches($script_name)
{
return (basename($_SERVER['SCRIPT_NAME'], '.php') == $script_name);
}
/**
* identifies the class for a given request
*/
function getClassForRequest($script_name)
{
return requestMatches($script_name) ? 'active' : '';
}
?>
<ul class="nav navbar-nav navbar-left">
<li class="<?=getClassForRequest('table')?>">
<a href="table.php">Table <span class="sr-only">(current)</span></a>
</li>
<li class="<?=getClassForRequest("index")?>">
<a href="index.php">home <span class="sr-only">(current)</span></a>
</li>
</ul>
By separating your logic in separate functions you can now easily address multiple situations if that would ever by the case. Observe that there is no need to echo from the function body, as <?= ?>
already does that for you.
In the end, I would add that this thing should be entirely handled on the client side. Here is an example, using jQuery.
<ul class="nav navbar-nav navbar-left" id="custom_menu">
<li>
<a href="table.php">Table <span class="sr-only">(current)</span></a>
</li>
<li>
<a href="index.php">home <span class="sr-only">(current)</span></a>
</li>
</ul>
<script>
$(function() {
var path = window.location.pathname;
var item = path.split('/').pop();
var element = $('#custom_menu a[href="' + item + '"]');
if (element.length == 0) {
// no elements match the current request uri
return false;
}
element.parent().addClass('active');
});
</script>