Duplicate array entries

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
markyb
Forum Newbie
Posts: 3
Joined: Wed Feb 03, 2010 7:25 am

Duplicate array entries

Post by markyb »

Hi,

I have an array, below, which contains duplicate values.

$corp =array(
131,
114,
111,
110,
135,
157,
152,
241,
240,
117,
360,
112,
240,
241,
242,
);

The array elements correspond to page ID numbers. I have used a foreach loop to cycle through the array and return page IDs before and after the current one and create links for these pages. For example, when on page 114, links are created for page IDs 131 (previous) and 111(next).

The code is:

foreach $corp as $key=>$value){

if ($value==$pageID){


$previousPageID = $theArray [$key-1];
$nextPageID = $theArray [$key+1];



}
}

This works fine until the loop comes to the duplicate values(for example 241). I want to be able to able to return a previous value of 152 and a next value of 240 (ie either side of the first 241), but the loop continues on and returns a previous value of 240 and a next of 242 (ie using the second instance of 241).

Does anyone know how to get around this problem? Thanks in advance...
User avatar
Grizzzzzzzzzz
Forum Contributor
Posts: 125
Joined: Wed Sep 02, 2009 8:51 am

Re: Duplicate array entries

Post by Grizzzzzzzzzz »

remove array duplicates?

http://php.net/manual/en/function.array-unique.php

or do you need them, found it abit hard trying to understand exactly what you want
markyb
Forum Newbie
Posts: 3
Joined: Wed Feb 03, 2010 7:25 am

Re: Duplicate array entries

Post by markyb »

Hi, thanks for replying...

Perhaps I didn't explain it that bit- yes, I do need the duplicates - I need to be able to produce different previous and next page IDs for both occurrences of 241.
User avatar
Eran
DevNet Master
Posts: 3549
Joined: Fri Jan 18, 2008 12:36 am
Location: Israel, ME

Re: Duplicate array entries

Post by Eran »

You are iterating over $corp, but inside the loop you are referring to $theArray. Is that a mistake or is there another array you aren't showing us?
markyb
Forum Newbie
Posts: 3
Joined: Wed Feb 03, 2010 7:25 am

Re: Duplicate array entries

Post by markyb »

Sorry - $theArray should be $corp here.
Post Reply