views:

71

answers:

4

Hi,

I have the following that stores the previous 10 URL's into a session:

function curPageURL() {
 $pageURL = 'http';
 if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
 $pageURL .= "://";
 if ($_SERVER["SERVER_PORT"] != "80") {
  $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
 } else {
  $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
 }
 return $pageURL;
}
//Insert Current URL in SESSION
       $CurrentPage = curPageURL();
       if(strpos($CurrentPage, '/products/'))
     {
     echo "<div class=\"title\">Recently viewed products</div>
<div id=\"recent\">";
       $_SESSION['pages'][] = $CurrentPage;
       if ( Count ( $_SESSION['pages'] ) > 10 )
     Array_Shift ( $_SESSION['pages'] );

How do I make sure only unique entries are stored?

Thanks, B

+3  A: 

instead of $_SESSION['pages'][] = $CurrentPage try $_SESSION['pages'][$CurrentPage] = 1

/edit: to keep items sorted, unset first:

 unset($_SESSION['pages'][$CurrentPage]);
 $_SESSION['pages'][$CurrentPage] = 1;
stereofrog
+1, in the absense of sets in PHP :(
Matthew Scharley
But this won't automatically push the other array items down. If they have visited this page 7 pages ago, the key for this item, which is probably what he using to output their page history, is still going to be whatever it was 7 pages ago, not moving it to the top or rearranging the other 6 pages, right?
Anthony
yes, you're right, however this wasn't a requirement, right? ;)post edited
stereofrog
+3  A: 
if(!in_array($CurrentPage, $_SESSION['pages']) {
    $_SESSION['pages'][] = $CurrentPage;
}
Anthony
A: 

Could array_unique be of help?

ChrisR
A: 

Just after

$_SESSION['pages'][] = $CurrentPage;

you need to add

$_SESSION['pages'] = array_unique($_SESSION['pages']);

Docs are available here

This method requires less processing, as it's a native function. Performing an 'if' on each item in the array could potentially be quite costly.

Rowan
thats the road i was tring to go down - however I get:Warning: array_unique() [function.array-unique]: The argument should be an array in???
Bift
sorry, my bad. pasted the wrong code. It's amended now, the above should work
Rowan