0

Please Help, i'm figuring out how to loop this certain html and php code. I'm stocked here.

for($x=1; $x<=10; $x++)
{
<li  <?php if (strpos($_SERVER['PHP_SELF'], $navserver[$x])) 
echo 'class="active"';?>><?     php echo '<a href="'.$navlink[$x].'">',
$navdesc[$x] ?></a></li>
}

4 Answers 4

1

Try this

<?php for($x=1; $x<=10; $x++) : ?>
    <li <?php if (strpos($_SERVER['PHP_SELF'], $navserver[$x])) echo 'class="active"';?>>
        <?php echo '<a href="'.$navlink[$x].'">' . $navdesc[$x] . '</a>'; ?>
    </li>
<?php endfor; ?>

Some wrongly written php code. you can read this echo manual for more understanding https://www.php.net/echo

Sign up to request clarification or add additional context in comments.

5 Comments

Welcome, if its working you can accept this answer or any other correct answer as well.
@crack, strpos could return 0 in which case it will not echo class active
actually I don't know the business logic for this script, so if strpos return zero then this class="active"0 will not print. may be that is expected result. @raj
@crack, yeah. possibly a bug
@crack yes crack it will print a blank, no class. :)
0

Hope this helps :

<?php 
for($x=1; $x<=10; $x++){ 
?>
<li    
   <?php 
     if (strpos($_SERVER['PHP_SELF'], $navserver[$x])) {  echo 'class="active"'; }
   ?>
>
   <a href="<?php echo $navlink[$x];?> "><?php echo $navdesc[$x] ?></a>

</li>

<?php } ?> 

You had wrong php syntax, unwanted html inside php tags.

Now the code is cleaned up.

Comments

0

Can you try this,

    for($x=1; $x<=10; $x++)
    {
        $Active ="";
        if(strpos($_SERVER['PHP_SELF'], $navserver[$x])){
            $Active = 'class="active"';
        }
         echo '<li  '.$Active.'> <a href="'.$navlink[$x].'">',$navdesc[$x].'</a></li>';
    }

Comments

0

try this it will make easier to you

<?php
for($x=1; $x<=10; $x++)
{
    $class_text = "";
    if(strpos($_SERVER['PHP_SELF'], $navserver[$x]))
    {
        $class_text = 'class="active"';
    }

?>
    <li <?php echo $class_text;?>><a href="<?php echo $navlink[$x];?>" ><?php echo $navdesc[$x];?></a></li>
<?php
}
?>

UPDATE : 2 or use can also use the below code

<?php
for($x=1; $x<=10; $x++)
{
    $class_text = "";
    if(strpos($_SERVER['PHP_SELF'], $navserver[$x]))
    {
        $class_text = 'class="active"';
    }
    echo '<li '.$class_text.'><a href="'.$navlink[$x].'" >'.$navdesc[$x].'</a></li>';
}
?>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.