Sarin Vadakkey Thayyil
Sarin Vadakkey Thayyil

Reputation: 954

Is to possible to use session arrays in php?

The following code always echos Not present. Can you please give me the solution?

  <?php

      session_start();
      $_SESSION[$ses_arr]=array();
      $word="cat";
      array_push($_SESSION[$ses_arr],$word);

      if(in_array($word,$_SESSION[$ses_arr]))
        {
         echo "present";
        }
      else
        {
         echo "Not Present";
        }

   ?>

Upvotes: 0

Views: 132

Answers (6)

SomeoneS
SomeoneS

Reputation: 1279

This should work:

<?php

  session_start();
  $ses_arr = array();
  $_SESSION['ses_arr']=$ses_arr;
  $word="cat";
  array_push($_SESSION['ses_arr'],$word);

  if(in_array($word,$_SESSION['ses_arr']))
    {
     echo "present";
    }
  else
    {
     echo "Not Present";
    }

?>

Upvotes: 0

Edward Ruchevits
Edward Ruchevits

Reputation: 6696

1) Use $_SESSION['ses_arr'] if 'ses_arr' is an index.

2) Use $_SESSION[ses_arr] if ses_arr is a predefined constant.

define('ses_arr','mySessionArray');

3) Use $_SESSION[$ses_arr] if $ses_arr is a predefined variable.

$ses_arr = 'mySessionArray';

The following code will work for you:

  <?php

  session_start();
  $_SESSION['ses_arr']=array();
  $word="cat";
  array_push($_SESSION['ses_arr'],$word);

  if(in_array($word,$_SESSION['ses_arr']))
    {
     echo "present";
    }
  else
    {
     echo "Not Present";
    }

  ?>

Upvotes: 0

mkey
mkey

Reputation: 212

this is vardump of your session array: [""]=> array(1) { [0]=> string(3) "cat" }

As you can see, because you haven't defined $ses_arr, its value is "" so "cat" is stored in $_SESSION[''][0]

Upvotes: 1

Ameer
Ameer

Reputation: 771

You are not telling PHP what the variable $ses_arr means. After session_start(); try $ses_arr = "ses_arr"; then it should work.

Upvotes: 0

Karl Laurentius Roos
Karl Laurentius Roos

Reputation: 4399

I can only assume that $ses_arr is some identifier you have to decide which key you'll use to save your data in, or that you've mistaken a string for a variable.

First and foremost, turn on errors by placing this at the top of your script right after <?php:

error_reporting(E_ALL);
ini_set('display_errors', 1);

If you've mistaken the string for a variable it will show errors. In that case, replace $sess_arr with 'sess_arr' and it should work flawlessly.

Upvotes: 0

Simone
Simone

Reputation: 21272

You haven't defined the $ses_arr variable.

Define it and your code will work.

Upvotes: 0

Related Questions