How to check that value exist in YII Session Variable

public function actionCartupdateajax() {

    //start yii session


    $session = Yii::app()->session;


    // get posted values


    $id = isset($_POST['id']) ? $_POST['id'] : "";


    $name = isset($_POST['name']) ? $_POST['name'] : "";


    $price = isset($_POST['price']) ? $_POST['price'] : "";


    $imgSrc = Yii::app()->request->baseUrl . '/images/icondeletecart.png';


    /*


     * check if the 'cart' session array was created


     * if it is NOT, create the 'cart' session array


     */


    if (!isset($session['cart_items']) || count($session['cart_items']) == 0) {


        Yii::app()->session['cart_items'] = array();


    }


    /*


     * Here is the proble


     *  check if the item is in the array, if it is, do not add 


     */


    if (in_array($id, Yii::app()->session['cart_items'])) {


        echo 'alreadyadded';


    } else {


        Yii::app()->session['cart_items'] = $id;


        echo '<li><strong>' . $name . '</strong><span>' . $price . '</span>'


        . '<img src=' . $imgSrc . ' alt="No Image" class="imagedeletecart" id=' . $id . '></li>';


    }


}
  1. $cart = Yii::app()->session->get(‘cart’) // will return null if nor ‘cart’ key in session;

  2. than U should populate $cart with your data

  3. than save this in session: Yii::app()->session->add(‘cart’, $cart);

not sure if I explained this right, feel free to ask if U need more info.

1 Like