0

How i can put string in a session?

for. e.g. : $_SESSION_[$questioncounter+'question'] = $accepted;

if _$questioncounter = 2_, this mean $_SESSION_['2question']

3
  • 1
    create an array instead then just push it inside, the question number and the status (accepted) Commented Aug 9, 2014 at 6:07
  • PHP string concatenation is done with the .. Also, it's $_SESSION, not $_SESSION_ Commented Aug 9, 2014 at 6:09
  • 1
    You may store an array into $_SESSION so there's no need to concatenate strings. Sounds weird to me ;) Why not using this approach $_SESSION['question'][5] = TRUE; having in mind your case. Commented Aug 9, 2014 at 6:11

2 Answers 2

4

Use a .(dot) to concat string and variable and remove _ from $_SESSION_ try

$_SESSION[$questioncounter.'question'] = $accepted;

so full code :-

<?php
session_start();
$questioncounter = 2;
$accepted = 'yes';
$_SESSION[$questioncounter.'question'] = $accepted;
echo $_SESSION['2question'];  // yes
?>
Sign up to request clarification or add additional context in comments.

Comments

0

Well, sometimes concatenation is needed but not in this case. Building variables by concatenating strings in this case would be the worst approach.

This is the way you should do things

// start session
if(!isset($_SESSION)){
    session_start();
}

// now, add your questions to the $_SESSION this way
$question = array('Is the sky really blue?', 'Should I stay or should I go?', 'Why I can\'t fly');
$_SESSION['question'] = $question;

// or this way
$_SESSION['question'][0] = 'Is the sky really blue?';
$_SESSION['question'][1] = 'Should I stay or should I go?';
...

// add their status this way
$_SESSION['question'][0]['accepted'] = 1; // or $_SESSION['question'][0]['status'] = 1;
$_SESSION['question'][1]['accepted'] = 0;

// and finally use them like this
echo $_SESSION['question'][0];

// or
if($_SESSION['question'][0]['accepted']){
    // say 'Bravo!'
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.