开发者

PHP foreach menu include

开发者 https://www.devze.com 2023-04-13 08:00 出处:网络
Im developing a website and I am trying to a foreach include for my header which includes my navigation menu (the main topic here).

Im developing a website and I am trying to a foreach include for my header which includes my navigation menu (the main topic here).

My code inside the header.php file for the navigation menu is here:

<!-- topmenu -->  
<div class="menu-header">
    <div class="container">
            <ul class="top menu">
            <?php
            $nav = array("Home","About","Portfolio","Products","Services","Contact");
            foreach($nav as $item){
            if($item == $title){
                echo "<li class='current-menu-ancestor parent'><a href='$item.php'>$item</a></li>";
                }else{
                echo "<li><a href='$item.php'>$item</a></li>"; }
                }
                ?>

          </ul>
        </div>
</div>        
<!--/ topmenu -->

You may开发者_运维百科 notice that in the code is the condition if($item == $title). In my index.php I have included $title="Home"; which I intended to be taken and used in this if statement.

On my index.php page I have included this with the following code:

<?php
    include("header.php");
$title = "Home";
?>

Can anyone tell me where I am going wrong?


Not an answer, but comments aren't suitable for formatted code. You might want to de-duplicate some of your HTML:

$class = '';
if($item == $title) {
    $class = ' class"current-menu-ancestor parent"';
}

echo "<li{$class}><a href='$item.php'>$item</a></li>";

Duplicating HTML as you did can lead to maintenance problems later on, if you decide to change something in the menu structure and change only one of the copies of the menu html.


header.php can not look into the future. If you want the variable to be set in the include, you need to set it before:

<?php
    $title = "Home";
    include("header.php");
?>

So you basically just switched the lines.

Additionally I suggest that you enable error reporting to the highest level when you develop, as it will give you warning on common mistakes that can happen while typing code.

You can do this by adding the following two lines to the top of your script:

error_reporting(~0);
ini_set("display_errors", "1″);

or by changing your PHP configuration.


You need to set $title before including header.php!

i.e.

<?php
    $title = "Home";

    include("header.php");
?>
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号