Reputation: 703
i have created an application where i want to apply active class on active page. Like if fike name starts with me_ then how can i apply class "active" to it.
here is my code:
$pageAttr = basename($_SERVER['REQUEST_URI']);
$files = array("me_dashboard.php","me_my_team.php","me_others.php","me_inbox.php","me_outbox.php");
<li class="<?php echo($pageAttr == $files[0] || $pageAttr == $files[1] || $pageAttr == $files[2] || $pageAttr == $files[3] || $pageAttr == $files[4]) ? "active":"" ?>"><a href="me_dashboard.php"><i class="icon-user icon-large"></i> Me</a></li>
this is not correct code to use. Please suggest me some other ways to achieve the solution in PHP.
Upvotes: 0
Views: 71
Reputation: 157384
If you have array of files like this
$files = array("me_dashboard.php",
"me_my_team.php",
"me_others.php",
"me_inbox.php",
"me_outbox.php"
);
Than you can use in_array()
like
<li class="<?php echo (in_array(basename($_SERVER['PHP_SELF']), $files) ? 'active' : '')?>">
It will be even better if you port the class=
attribute in the if
condition as well, so that you do not get an empty class=""
markup.
If you want to refactor your code more, consider porting entire code in a function
, and then return
the value if condition goes true
.
As commented, you wanted to fetch the prefix of the file than you can use substr()
<?php
$page_name = 'me_dashboard.php';
$fetch_prefix = substr($page_name, 0, 3);
echo $fetch_prefix;
?>
<li class="<?php echo (($fetch_prefix == 'me_') ? 'active' : '')?>">A</li>
Upvotes: 2
Reputation: 9635
you can try this one
<?php
$pageAttr = basename($_SERVER['REQUEST_URI']);
$files = array("me_dashboard.php","me_my_team.php","me_others.php","me_inbox.php","me_outbox.php");
foreach($files as $file)
{
$class_text = "";
if($file==$pageAttr)
{
$class_text = ' class="active" ';
}
?>
<li <?php echo $class_text;?> ><a href="<?php echo $file;?>"><i class="icon-user icon-large"></i> Me</a></li>
<?php
}
?>
Upvotes: 1