twan twan - 2 months ago 4
PHP Question

Prevent duplicate ids from being added to session (array)

I got a session which adds ids to an array, the problem is every id gets added even if the id is already present. How can I prevent duplicate id's from being added to the array?

I figured I need to check for the id using in_array but I don't know exactly how to use it correctly.

I send the id of the product to my quote page using this link:

<p><a class="offertelink" href="offerte.php?product='.$productcr[0]['id'].'">Request a quote</a></p>

Then on that page I use the following code:

$_SESSION['product'] = array();

if( isset($_GET['product'])){
$_SESSION['product'][] = $_GET['product'];
$prods = implode(",", $_SESSION['product']);

And finally load all the products with the ids that are inside the array:

if(count($_SESSION['product']) != 0){
// offerte overzicht
$offerte = "SELECT * FROM `snm_content` WHERE `id` in (".$conn->real_escape_string($prods).") AND state = 1";
$offertecon = $conn->query($offerte);
$offertecr = array();
while ($offertecr[] = $offertecon->fetch_array());

But now everytime I reload the page, the id is added again, it's not really bad since the products are only loaded once, but still I would like to fix this, because I think a query checking for tons of duplicate ids is not the best way.


Using in_array is simple - you just check if element is in array:

var_dump(in_array($element, $array));

In your case it is:

var_dump(in_array($_GET['product'], $_SESSION['product']));

And the check is:

// i advise you to check product value as `int`.  
// Because values as `empty string` or `0` or `false` are considered set
if( 0 < intval($_GET['product']) && !in_array($_GET['product'], $_SESSION['product']) ) {
    $_SESSION['product'][] = $_GET['product'];

But the more clever solution is to use product id as an array key with some fixed value (1 or true for example):

$_SESSION['product'] = [
    '101' => 1,
    '102' => 1,
    '106' => 1,

In this case you don't even need to check if your key exists - if it exists it will be overwritten, if not - will be added:

if( 0 < intval($_GET['product']) ) {
    $_SESSION['product'][ $_GET['product'] ] = 1;
// but here you need to take array keys instead of values
$prods  = implode(",", array_keys($_SESSION['product']));