Jump to content

[SOLVED] Help - For loop Array menu duplication


rahish

Recommended Posts

This should be easy for someone. I am trying to populate a simple html list menu with urls and link text using an array and a for loop.

 

I cannot work out what I am doing wrong but I know I am only guessing, I have got my for loops mixed up and it is duplicating the output.

 

 

Here is the example



<?php
$menu_link = array (0 =>'index.php', 'info.php', 'contact.php');
$menu_text = array (0 =>'Home', 'Information', 'Contact');


?>


<h3> Menu Example</h3>

<?php  


print_r($menu_link);
print_r($menu_text);
?>
<?php



echo "<ul>";
for ($text=0; $text < sizeof($menu_text); $text++) {


for ($i=0; $i < sizeof($menu_link); $i++) {
echo  "<li><a href='", $menu_link[$i], "'>$menu_text[$text] "; //$i,


//echo  " ",$menu_text[$text], "</li>";

	}	

}


echo "</a></li>";

echo "</ul>";

?>

$menu_link = array (0 =>'index.php', 'info.php', 'contact.php');
$menu_text = array (0 =>'Home', 'Information', 'Contact');
$items=count($menu_link);
for ($i=0;$i<$items;$i++) {
  echo '<a href="'.$menu_link[$i].'">'.$menu_text[$i].'</a>';
}

Just thought - probably a better way is this:

  $arrLinks=array('index' => 'Home Page',
                  'info' => 'Information',
                  'contact' => 'Contact');
  foreach ($arrLinks as $key => $val) {
    echo '<a href="'.$key.'.php">'.$val.'</a>';
  }

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.