twan
twan

Reputation: 2659

How can I add new items to my session array if value is not already in it? PHP

I am trying to add new items to my array if they don't already exist but below code shows me an error:

// Check if session exists
if(!isset($_SESSION['coupon'])){
  // Create array from session
  $_SESSION['coupon']['couponcode'] = array();
}

if(!isset($_SESSION['coupon']['couponcode'][$coupon])){
  // Add couponcode to session if it does not already exist
  $_SESSION['coupon']['couponcode'][] = $coupon;
}

$_SESSION['coupon']['couponcode'][] = $coupon;

Gives: PHP Fatal error: Uncaught Error: [] operator not supported for strings

But I thought this was the way to add to the array, if I remove the brackets it just replaces the value everytime.

I have session_start(); everywhere at the top of my pages.

Upvotes: 2

Views: 295

Answers (2)

Abhay Maurya
Abhay Maurya

Reputation: 12277

First of all,do not put blindly session_start() on top of every page. It will start session again even if a previous session was running and will refresh your all values, so first thing, change that to:

if (session_status() == PHP_SESSION_NONE) {
   session_start();
}

this way it starts the session only if it doesn't exist.

Now, you are getting error because somehow your $_SESSION['coupon']['couponcode'] is a string so add an additional check:

if(!isset($_SESSION['coupon']['couponcode'][$coupon])){
  // Add couponcode to session if it does not already exist
  if (empty($_SESSION['coupon']['couponcode']) || !is_array($_SESSION['coupon']['couponcode']))) {
      $_SESSION['coupon']['couponcode'] = [];
  }
  $_SESSION['coupon']['couponcode'][] = $coupon;
}

Upvotes: 1

Ashu
Ashu

Reputation: 1320

You can use array_push():

if(empty($_SESSION['coupon'])){
   // Create array from session
   $_SESSION['coupon']['couponcode'] = array();
}
else
{
  if(!in_array( $coupon,$_SESSION['coupon']['couponcode'])) //check in array available
  {
    array_push($_SESSION['coupon']['couponcode'], $coupon); //push to array
  }
} 

Upvotes: 2

Related Questions