Jump to content

Making the Array go into an If/else if statement


JREAM

Recommended Posts

Hey I have this array printing out a menu, it works nice,

But I can't seem to make my $_GET receive the right array.

 

Would anyone be so kind to give me some insight :)

 

I shortened it up so I hope it doesnt waste anyone time:

<?php

#Here's the array and foreach loop
$nav_menu[] = "123";
$nav_menu[] = "abc";
$nav_menu[] = "!@#";

foreach ($nav_menu as $nav_link) {
  print '<li><a href="index.php?page=' . $nav_link . '">' . $nav_link . '</a></li>';
}

# Below is suppsed to GET a page titled from the foreach list and do the function assigned to it:
if ($_GET['page'] == $nav_link) {
  section_00();
}
else if ($_GET['page'] == $nav_link) {
  section_01();
}
# NOTE: There will be more Else-If's

# This will just be the functions to do something.
function section_00(){
print '00';
}

function section_01(){
print '01';
}

?>

Oh I see, this kind of goes back to my first question I had now with Globals.

 

I put the IF statement in the Loop but it gets a bit whacky,

 

When I globalize it something is funky, I can't see the IF statement when parsed so Im having trouble visualizing it,

are you able to see what Is wrong with this:

 

foreach ($nav_menu as $nav_link) {
  print '<li><a href="index.php?page=' . $nav_link . '">' . $nav_link . '</a></li>';
}
global $nav_link;
if ($_GET['page'] == $nav_link) {section_00();
} else if ($_GET['page'] == $nav_link) {section_01();

}

Your problem is occurring because you don't understand the flow of the script and how it is used.

 

The foreach loop sets up the links, which are displayed. When a user clicks on one, the script is invoked again.

 

You probably want something like this:

<?php
$nav_menu = array('one'=>'section01','two'=>'section02','three'=>'section03');
if (isset($_GET['page'])) 
    foreach ($nav_menu as $page => $sect)
           if ($_GET['page'] == $page) $$sect();

foreach ($nav_menu as $nav_link => $dmy) {
  echo '<li><a href="?page=' . $nav_link . '">' . $nav_link . '</a></li>';
}
?>

 

(note: untested)

 

Ken

It's just a dummy variable which isn't used in this particular loop.

 

Do these two loops and compare the output:

<?php
$nav_menu = array('one'=>'section01','two'=>'section02','three'=>'section03');
//
echo 'loop 1<br>';
//
foreach ($nav_menu as $page => $dmy)
     echo '$page: ' . $page . '<br>';
//
echo 'loop 2<br>';
foreach ($nav_menu as $page)
     echo '$page: ' . $page . '<br>';
?>

 

Ken

 

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.