Jump to content

include() with pages array


cougar23

Recommended Posts

I've got an array of pages on in my site, which the key gets set based on the button clicked and stored in a POST variable $page which comes from my navigation menu which is a form that gets submitted on button click, and i'm trying to do an include() with the $page value matched with an the array of pages, but I'm getting and "undefined index" error.  I know the pageName variable is set correctly and it works fine if i manually enter into the include what i'm trying to build (i.e. manually doing include('home.php'); ).  Anyone know that the problem could be?

 

$page = $_POST('pageName');
$pages = new array ('home' => 'home.php', 'about' => 'about.php' );
include( $pages[$page] );

Link to comment
https://forums.phpfreaks.com/topic/108379-include-with-pages-array/
Share on other sites

That's what I have. sorry i dont have the code in front of me so I wrote it up and made that typo.  The value of $page is stored correctly (verified via echo).  The problem is occurring with the keys/array on the include() line.

 

For exampe include($page.'.php'); work fine, but include($pages[$page]); is giving the undefined index error.

$pages = array ( 'home' => 'home.php',
                 'about' => 'about.php',
                 'performances' => 'performances.php',
                 'contact' => 'contact.php');

if( !isset($_POST['page']) ) $page = 'home';
else $page = $_POST['page']);

include($pages[$page]);

Make sure the requested page ($page) is in the $pages array too.

 

Change

if( !isset($_POST['page']) ) $page = 'home';
else $page = $_POST['page']);

to

$page = (isset($_POST['page']) && !empty($_POST['page'])) ? $_POST['page'] : 'home';

// check that the requested page exists
if(array_key_exists($page, $pages))
{
    include $page;
}

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.