Page 1 of 1

extract one item from an array?

Posted: Sun Feb 28, 2010 1:49 am
by Benjipie
Hi,

I have an array that checks what page of a website the user is currently looking at. On each of my webpages i have this bit of code that gets the name of the page:

Code: Select all

$currentPage = basename($_SERVER['SCRIPT_NAME'])
On a different php page i then have an array like this which just stores a list of the pages i want to check, this is then used as include file in the other pages.

Code: Select all

$deepLinkedPages = array('about_us.php', 'index.php', 'contact_us.php');

I then check through the array to see what page the user is looking at using this code:

Code: Select all

 
foreach ($deepLinkedPages as $page) {
if ($currentPage == $page) {
...display footer 1...
}else{
display footer 2
 


The problem I am having is if there are 6 pages in the array (the $deepLinkedPages array) then i get 6 footers on the page. If there are 2 pages in the array I get 2 footers. I think this is because I am using a foreach loop, but i've tried using while loop and cannot get this to work.

Where am I going wrong with this?

Thanks for any help.

Re: extract one item from an array?

Posted: Sun Feb 28, 2010 10:18 am
by davex
The problem is that is loops through every page as you have noticed.

This can be corrected by putting in a $is_in_list flag which starts false and gets set in the foreach loop but this is unnecessarily messy.

I think you'll find in_array will work for your purposes:

Code: Select all

 
if (in_array($deepLinkedPages,$page) {
..display footer 1 (page IS in array)
} else {
.. display footer 2 (page NOT in array)
}
 

Re: extract one item from an array?

Posted: Sun Feb 28, 2010 5:45 pm
by Benjipie
Thanks davex,

It worked great!!
Ben.

Re: extract one item from an array?

Posted: Sun Feb 28, 2010 11:53 pm
by davex
No problem - happy to help.

Cheers,

Dave.