PHP Help

I am pretty new to php and need some help from the pros out there.

I am constructing this site which is made up of the following:
header.php
sidebar.php
footer.php
index.php
contact.php
about.php
services.php

However my sidebar NOT a static sidebar and MAY change based on which page is visited.
So instead of having different sidebars, like
sidebar1.php
sidebar2.php
sidebar3.php
Is it possible to have one dynamic sidebar.php that will load different files based on which page you are on? The different files for the sidebar are:
oranges.php
grapes.php
managoes.php
limes.php

So sometimes 2 of the 4 is listed in the sidebar, sometimes 3 and sometime all 4 is included, based on the page you are on.

Is there a way to achieve this instead of the basic
<?PHP include “sidebar1.php”; ?>
<?PHP include “sidebar2.php”; ?>
<?PHP include “sidebar3.php”; ?>

Like having a sidebar.php which will have different php include files?

Can someone help me with a script if this is possible?

Thanks

Take a look at PHP: elseif/else if - Manual

I learned PHP from the ground up. Would it be better today for some to start with a framework? I feel this could be the case for some, and would have been better for me IMO as I had a hard time getting away from procedural coding.

Consider this:

sidebar.php


<?php
$menu = array();

$menu['default'] = array(1);
$menu['oranges'] = array(1,2,3);
$menu['grapes'] = array(2,4);
// and so on
 
function getMySidebarItems($page){
  global $menu;
  if( array_key_exists($page, $menu)){
  return $menu[$page];
  }
  else {
  return $menu['default'];
  }
}

oranges.php


<?php
$this_page = 'grapes';
include 'sidebar.php';

foreach(getMySidebarItems($this_page) as $item){
// using echo to illustrate, but you could include files here
echo "include 'sidebar" . $item . ".php'";

// uncomment out this example
// include 'sidebar' . $item . '.php';

}


For the sake of of illustration oranges.php, sidebar.php and sidebar1.php etc are all in the same folder, or as should be, the include files are well above your /html directory and are where PHP can find them one of the php include paths.

So, each file ‘knows’ its name and that is set in the file eg ‘grapes’ - but control of which sidebar appears where is maintained centrally in the $menu array.

There are lots of ways of elaborating and/or simplifying this - but ostensibly you have to maintain your list of pages <-> menu items in some kind of static fashion, here I am just using PHP arrays.

If you suddenly add a new page, ‘grapefruit’ but fail to assign an array for it in $menu, then you should get $menu[‘default’].