extract one item from an array?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Benjipie
Forum Newbie
Posts: 11
Joined: Sun Dec 07, 2008 7:04 am

extract one item from an array?

Post 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.
davex
Forum Contributor
Posts: 101
Joined: Sat Feb 27, 2010 4:10 pm
Location: Namibia

Re: extract one item from an array?

Post 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)
}
 
Benjipie
Forum Newbie
Posts: 11
Joined: Sun Dec 07, 2008 7:04 am

Re: extract one item from an array?

Post by Benjipie »

Thanks davex,

It worked great!!
Ben.
davex
Forum Contributor
Posts: 101
Joined: Sat Feb 27, 2010 4:10 pm
Location: Namibia

Re: extract one item from an array?

Post by davex »

No problem - happy to help.

Cheers,

Dave.
Post Reply