Jump to content

Trying to use loop to create menu list from array


jp612

Recommended Posts

I have created my menu using a multi dimensional array like so:

 

<?php 
$menu = array(
		"1" => array (
				"title" => Home,
				"page"	=> home, 
				"url"	=> "../content/home.php"
					),
		"2" => array (
				"title" => "Our Services",
				"page"	=> services,
				"url"	=> "../content/services.php"		
					),					
		"3" => array (
				"title" => Portfolio,
				"page"	=> portfolio,
				"url"	=> "../content/portfolio.php"		
				),
	"4" => array (
				"title" => About,
				"page"	=> about,
			"url"	=> "../content/about.php"		
					),			
	"5" => array (
				"title" => Contact,
				"page"	=> contact,
				"url"	=> "../content/contact.php"		
					)
);
?> 

 

for this format:

 

<li> <a href='index.php?page='<?php $menu['1'] "page" ?>'></a><?php $menu['1'] "title" ?></li>

 

how do i make it a loop that changes the number next to $menu accordingly?

 

then in my content file i have to make it include the content file

 

<?php 
if($_GET['page'] == "services") {
include("includes/design.html");
}else if($_GET['page'] == "about") {
include("includes/graphic.html");
}else if($_GET['page'] == "contact") {
include("includes/contact.php");
}else if($_GET['page'] == "portfolio") {
include("includes/about.html");
}else{
	include("includes/home.php");
}
?>

 

Is there a better way to do it rather than using if , elseif? I know its possible to do something thats just 1 line long but i cant remember it.

Link to comment
Share on other sites

You have some errors in your PHP code to your menu that (I hope) you are getting error messages about. Here is corrected code that includes a loop that generates the nav. Also, keep in mind that arrays traditionally start with 0, rather than 1 like your array.

 

 <?php 
$menu = array(
               "1" => array (
                               "title" => 'Home',
                               "page"  => 'home', 
                               "url"   => "../content/home.php"
                                       ),
               "2" => array (
                               "title" => "Our Services",
                               "page"  => 'services',
                               "url"   => "../content/services.php"            
                                       ),                                      
               "3" => array (
                               "title" => 'Portfolio',
                               "page"  => 'portfolio',
                               "url"   => "../content/portfolio.php"           
                                       ),
               "4" => array (
                               "title" => 'About',
                               "page"  => 'about',
                               "url"   => "../content/about.php"               
                                       ),                      
               "5" => array (
                               "title" => 'Contact',
                               "page"  => 'contact',
                               "url"   => "../content/contact.php"             
                                       )
);
?> 

<ul>
<?php
for ($i = 1; $i <= count($menu); $i++)
{
	echo '<li><a href="index.php?page=' . $menu[$i]['page'] . '">' . $menu[$i]['title'] . '</a></li>';
}
?>
</ul>

For the second item, you could do this (untested, but I believe it should work):

 

<?php
   if (isset($_GET['page'])) { 
         if (file_exists("includes/" . htmlentities($_GET['page'], ENT_QUOTES) . ".php")) 
         { 
             include("includes/" . htmlentities($_GET['page'], ENT_QUOTES) . ".php"]); 
         } 
         else 
         { 
            include("includes/home.php"); 
         }
     } 
         else 
         { 
            include("includes/home.php"); 
         }
?>

I don't think this is the way to go though. I'm a bit nervous about the security issues involved with including a file based entirely on what is entered in the URL.

Link to comment
Share on other sites

Thanks. I still have a bit of trouble understanding loops. So the $i is a variable that defines the starting value and by using $i++ makes it go up by one number each time the loop is run. The count function is able to count my array items which are numbers. Is all this correct?

 

But why is it $i <= count($menu)??

 

<?php
   if (isset($_GET['page'])) { 
         if (file_exists("includes/" . htmlentities($_GET['page'], ENT_QUOTES) . ".php")) 
         { 
             include("includes/" . htmlentities($_GET['page'], ENT_QUOTES) . ".php"]); 
         } 
         else 
         { 
            include("includes/home.php"); 
         }
     } 
         else 
         { 
            include("includes/home.php"); 
         }
?>

 

why could the above method be a security risk? Is it like the $GET function that presents a security risk because everything has to be put into the url so its possible to manipulate it?

 

also how does the htmlentites know which include file to include??

Link to comment
Share on other sites

To explain a for loop...

 

-- The first part, "$i = 1;" defines a temporary variable called $i, and sets it to 1. I would usually set it to "0", but your particular array starts with 1.

 

-- The second part, "$i <= count($menu)" says that the loop will run while $i is less or equal to the number of items in $menu. The count() function counts the number of items in the menu array, so another way to look at that section is "$i <= 5." I used count() rather than 5, however, since I want the loop to work if you add or subtract items from the menu.

 

-- The final part, $i++, says that at the end of every loop, 1 will be added to $i.

 

why could the above method be a security risk? Is it like the $GET function that presents a security risk because everything has to be put into the url so its possible to manipulate it?

I am not a PHP security expert. I'm just not totally comfortable with including files based entirely on the URL, since the URL is so easy to change by the user. It should be safe -- I make sure the file actually exists before including it, and also run htmlentities() to strip unsafe characters from the URL, but as I said, I'm not a security expert. It just makes me uneasy, and I don't want to provide advice without at least attempting to explain the potential issues with it.

 

To explain what that section does in plain English, it checks if the page variable is set in the URL using $_GET['page']. If so, it grabs that variable, and checks to see if there is a properly named include file: "includes/[page variable].php." The htmlentities() function is used to clean the input, in case the user tries to add something malicious. If the file exists, I include it. If not, or if the page variable is not set, I include the home.php include.

Link to comment
Share on other sites

To explain a for loop...

 

-- The first part, "$i = 1;" defines a temporary variable called $i, and sets it to 1. I would usually set it to "0", but your particular array starts with 1.

 

-- The second part, "$i <= count($menu)" says that the loop will run while $i is less or equal to the number of items in $menu. The count() function counts the number of items in the menu array, so another way to look at that section is "$i <= 5." I used count() rather than 5, however, since I want the loop to work if you add or subtract items from the menu.

 

-- The final part, $i++, says that at the end of every loop, 1 will be added to $i.

 

 

I am not a PHP security expert. I'm just not totally comfortable with including files based entirely on the URL, since the URL is so easy to change by the user. It should be safe -- I make sure the file actually exists before including it, and also run htmlentities() to strip unsafe characters from the URL, but as I said, I'm not a security expert. It just makes me uneasy, and I don't want to provide advice without at least attempting to explain the potential issues with it.

 

To explain what that section does in plain English, it checks if the page variable is set in the URL using $_GET['page']. If so, it grabs that variable, and checks to see if there is a properly named include file: "includes/[page variable].php." The htmlentities() function is used to clean the input, in case the user tries to add something malicious. If the file exists, I include it. If not, or if the page variable is not set, I include the home.php include.

 

Cool! I finally get loops now. that opened a lot of php doors for me. :)

 

BTW: I also had a look at the killerphp OOP PHP tutorial. I just have one question about that and functions in general if i define a function,constant,class in a different file i.e class_lib.php or function_lib.php. If i then call it in another file thats in another folder or on the same level how does it (or does it) know that that function, constant, class was defined in some file in my website folder somewhere?

Link to comment
Share on other sites

if i define a function,constant,class in a different file i.e class_lib.php or function_lib.php. If i then call it in another file thats in another folder or on the same level how does it (or does it) know that that function, constant, class was defined in some file in my website folder somewhere?

Just to be clear, you do need to include all the files you use -- just creating a file with a class in it doesn't automatically make it available to the rest of the application. Wherever you plan to create an object using that class, you need to include the class file.

 

I believe that may answer your question? If you include it, PHP is smart enough to figure out the rest.

Link to comment
Share on other sites

Just to be clear, you do need to include all the files you use -- just creating a file with a class in it doesn't automatically make it available to the rest of the application. Wherever you plan to create an object using that class, you need to include the class file.

 

I believe that may answer your question? If you include it, PHP is smart enough to figure out the rest.

 

 

Ahh I see. Cool, thanks.

Link to comment
Share on other sites

So if I want to put my array and loop into a class along with the second item. Would i do it something like this?

<?php

class header_menu {

var $menu = array(
		"1" => array (
				"title" => 'Home',
				"page"	=> 'home', 
				"url"	=> "../content/home.php"
					),
		"2" => array (
				"title" => "Our Services",
				"page"	=> 'services',
				"url"	=> "../content/services.php"		
					),					
		"3" => array (
				"title" => 'Portfolio',
				"page"	=> 'portfolio',
				"url"	=> "../content/portfolio.php"		
				),
	"4" => array (
				"title" => 'About',
				"page"	=> 'about',
			"url"	=> "../content/about.php"		
					),			
	"5" => array (
				"title" => 'Contact',
				"page"	=> 'contact',
				"url"	=> "../content/contact.php"		
					)
);	

function menu_loop() {

   	for ($i = 1; $i <= count($menu); $i++)
   	{
   		echo '<li><a href="index.php?page=' . $menu[$i]['page'] . '">' . $menu[$i]['title'] .'</a></li>';
   	};

}

function get_main_menu() {

	echo "<ul>";
	echo menu_loop();
	echo "</ul>";
}




}


?>

 

I dont know how to get further than this. I also dont know where to use any $this-> type stuff. Since all variables are already defined do i still have to inistiate it? or is using a class a bit over the top for this??

Link to comment
Share on other sites

If this is the only function of your class, I think putting this in a class is over the top. I have found that one of the main advantages of object oriented PHP is that I can use it to combine similar functionality, creating objects that have specific tasks. For example, to reference a recent screencast I did on this, I may have an "Auth" object that handles all authorization functionality, or a "Template" object that deals with storing variables used in my views and displaying the views themselves. Creating an object whose only purpose is to display your menu seems unnecessary.

 

While I won't put this in a class, I would perhaps make it a function, and place it in a .php file that includes other similar functions. You could then include the php file and call the function:

 

<? include("yourfile.php");
display_menu();
?>

 

<?php

function display_menu() 
{

    $menu = array(
               "1" => array (
                               "title" => 'Home',
                               "page"  => 'home', 
                               "url"   => "../content/home.php"
                                       ),
               "2" => array (
                               "title" => "Our Services",
                               "page"  => 'services',
                               "url"   => "../content/services.php"            
                                       ),                                      
               "3" => array (
                               "title" => 'Portfolio',
                               "page"  => 'portfolio',
                               "url"   => "../content/portfolio.php"           
                                       ),
               "4" => array (
                               "title" => 'About',
                               "page"  => 'about',
                               "url"   => "../content/about.php"               
                                       ),                      
               "5" => array (
                               "title" => 'Contact',
                               "page"  => 'contact',
                               "url"   => "../content/contact.php"             
                                       )
       );    

       echo "<ul>";
       for ($i = 1; $i <= count($menu); $i++)
       {
               echo '<li><a href="index.php?page=' . $menu[$i]['page'] . '">' . $menu[$i]['title'] .'</a></li>';
       };
       echo "</ul>";
}


?>

Link to comment
Share on other sites

ok i made a function containing the script.

ahh i seem to have more problems. What I want to create a dynamic html page title which grabs stuff from the array depending on which page is included. So i created this

 

<?php
if(isset($GET['page'])) {
	if($GET['page'] == $menu[$i]['page'] ) {
		echo $menu[$i]['page'];
	}else{
		echo "Error!";
	}
}else{
		echo "Error!";
}
}

?>

 

however the isset already fails since the array is loaded later in the document (I also have no idea if the above script will work). So i figured that i'd give my function some parameters so i can only load the array at the start. But how do i put a large chunk of code in a parameter? ( I cant pack it all into a variable.)

Edited by jp612
Link to comment
Share on other sites

Something like this?

 

<?php
function get_menu(){
$return = array(
	"1" => array (
		"title" => 'Home',
		"page"  => 'home', 
		"url"   => "../content/home.php"
	),
	"2" => array (
		"title" => "Our Services",
		"page"  => 'services',
		"url"   => "../content/services.php"
	),
	"3" => array (
		"title" => 'Portfolio',
		"page"  => 'portfolio',
		"url"   => "../content/portfolio.php"
	),
	"4" => array (
		"title" => 'About',
		"page"  => 'about',
		"url"   => "../content/about.php"
	),
	"5" => array (
		"title" => 'Contact',
		"page"  => 'contact',
		"url"   => "../content/contact.php"
	)
);

return $return;
}

function display_menu($menuItems){
$return = "<ul>"

for ($i = 1; $i <= count($menuItems); $i++){
	$return .= '<li><a href="index.php?page=' . $menuItems[$i]['page'] . '">' . $menuItems[$i]['title'] .'</a></li>';
};

$return .= "</ul>";

return $return;
}

$menu = get_menu();


if(isset($GET['page'])) {
if($GET['page'] == $menu[$i]['page'] ) {
	echo $menu[$i]['page'];
}else{
	die("Error!");
}
}else{
die("Error!");
}
?>

<div class="menu"><?php echo display_menu($menu); ?></div>

Link to comment
Share on other sites

since my most of my stuff to do with the $GET['page'] function and the loops variale $i is called later in the document (and has to be) does that mean my function that puts in the title at the top of the html page isnt going to work since almost everything used in it will be defined later?

 

if(isset($GET['page'])) {
       if($GET['page'] == $menu[$i]['page'] ) {
               echo $menu[$i]['page'];
       }else{
               die("Error!");
       }
}else{
       die("Error!");
}
?>

Link to comment
Share on other sites

Why define it later? You can have php code before any HTML. Sorry my previous one won't work. This is more clear I hope:

 

<?php
function get_menu(){
       $return = array(
               "1" => array (
                       "title" => 'Home',
                       "page"  => 'home', 
                       "url"   => "../content/home.php"
               ),
               "2" => array (
                       "title" => "Our Services",
                       "page"  => 'services',
                       "url"   => "../content/services.php"
               ),
               "3" => array (
                       "title" => 'Portfolio',
                       "page"  => 'portfolio',
                       "url"   => "../content/portfolio.php"
               ),
               "4" => array (
                       "title" => 'About',
                       "page"  => 'about',
                       "url"   => "../content/about.php"
               ),
               "5" => array (
                       "title" => 'Contact',
                       "page"  => 'contact',
                       "url"   => "../content/contact.php"
               )
       );

       return $return;
}

function display_menu($menuItems){
       $return = "<ul>"

       for ($i = 1; $i <= count($menuItems); $i++){
               $return .= '<li><a href="index.php?page=' . $menuItems[$i]['page'] . '">' . $menuItems[$i]['title'] .'</a></li>';
       };

       $return .= "</ul>";

       return $return;
}

$menu = get_menu(); ?>
<html>
<head>
<title>
<?php if(isset($GET['page'])) {
$index = 0;
$page = $_GET['page'];
for($i=1; $i <= count($menu); $i++){
               if($page == $menu[$i]['page'] ) {
		$index = $i;
	}
}

if($index != 0){
	echo $menu[$index]['page'];
}else{
	echo "Error!";
}
}else{
       echo "Error!";
}
?>
</title>
</head>
<body>
<div class="menu"><?php echo display_menu($menu); ?></div>
</body>
</html>

Link to comment
Share on other sites

ohh yes, I have to use a for loop not just a if statement for the title thing.

 

Now all of a sudden i cant use variables i defined in another function, this is my functons.php which i included into my index:

 

<?php



// Navbar top. Use array to add content.
function get_mainmenu_array() {

$menu = array(
		"1" => array (
				"title" => 'Home',
				"page"	=> 'home', 
				"url"	=> "../content/home.php",
				"desc_title" => "Web Design Services - Affordable Web And Graphic Design Services | Debes Design"	
					),
		"2" => array (
				"title" => "Our Services",
				"page"	=> 'services',
				"url"	=> "../content/services.php",
				"desc_title" => "Our Services - Static Websites, Dynamic Websites And Content Management Systems | Debes Design"			
					),					
		"3" => array (
				"title" => 'Portfolio',
				"page"	=> 'portfolio',
				"url"	=> "../content/portfolio.php",
				"desc_title" =>	"Our Portfolio - Our Recent Web Design Work | Debes Design"	
				),
	"4" => array (
				"title" => 'About',
				"page"	=> 'about',
			"url"	=> "../content/about.php",		
				"desc_title" =>	"About Us | Debes Design"	
				),			
	"5" => array (
				"title" => 'Contact',
				"page"	=> 'contact',
				"url"	=> "../content/contact.php",
			"desc_title" =>	"Contact Us - Get A Free Quote About Any Design Work | Debes Design"			
					)
);             	 	
}


function get_mainmenu(){

echo "<ul>";
      	for ($i = 1; $i <= count($menu); $i++)
   	{
   		echo '<li><a href="index.php?page=' . $menu[$i]['page'] . '">' . $menu[$i]['title'] .'</a></li>';
   	};
       echo "</ul>";

}




// dynamic title
function html_title() {
if(isset($GET['page'])) {
	$title = 0;
	$page = $GET['page'];
	for ($i = 1; $i <= count($menu); $i++) {
		if($page == $menu[$i]['page'] ) {
                       $title = $i;
               }else{ echo "Error! No Page"; }

	}
if($title != 0) {
	echo $menu[$title]['desc_title'];

}else{ echo "Error! Title = 0"; }
}else{ echo "Error! GET page not set"; }
}

//Show content works with menu, put in content
function get_content() {

if(isset($GET['page'])) {
if(file_exists("includes/views/" . htmlentities($GET['page'], ENT_QUOTES). ".php")) {
	include("includes/views/" . htmlentities($_GET['page'], ENT_QUOTES) . ".php");
}else{
	include("includes/views/home.php");
}
}else{
	include("includes/views/home.php");
}

}



?>

 

Problem is when the first for loop playes i get the error that the function $menu is undefined. Which is my array at the top. Why?

 

I packed the array into a function and before i just loaded it like so in the title before the second loop:

 

get_mainmenu_array();

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...