Jump to content

[SOLVED] Question about looping


blatant3

Recommended Posts

Hello everyone. This is my first post to the forums so first I would like to say hello to everyone.

The question I have is this:

I am designing a website and I want to incorporate a system that will look at the URL and decide which include to use.

I have everything working using some code like this:

<?php
$path = $_SERVER['PHP_SELF'];
$page = basename($path);
$page = basename($path, '.php');

if($page == "index") {
include('includes/index.inc');
}
elseif($page == "someOtherPage") {
include('includes/someOtherPage.inc');
}
else {
echo 'blah blah blah';
?>

 

As you can see this can get redundant really fast.

What I want to do is store all of the page names in an array and loop through them, including the page that matches the conditional, But I cant figure out how to get it to work.

 

Any suggestions?

 

Thanks in advance :)

Link to comment
https://forums.phpfreaks.com/topic/115859-solved-question-about-looping/
Share on other sites

Try this (some editing may need to be done still, not tested):

$path = $_SERVER['PHP_SELF'];
$page = basename($path);
$page = basename($path, '.php');

$myArray = ('index','someOtherPage','anotherPage');

foreach($myArray as $pa){
     if($page == $pa) {
          include('includes/'.$pa.'.inc');
          break;
     }else{
          echo 'Page Not Found';
     }
}

I wouldn't do that because you'd get "Page not found" every time you iterated before the page was found.  I'd personally do:

 

 

$pages = array('home', 'contact', 'aboutus', 'something);

if (in_array(strtolower($_GET['page']), $pages)) {

  include ("{$_GET['page']}.php");

}

better to use in_array

 

//               page name          page path
$pages = array( 'index'         => 'includes/index.inc',
               'someotherpage' => 'includes/someotherpage.inc'
             );

if(in_array($requested_page_var, $pages))
{
   include $pages[$requested_page_var];
}

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.