1

I'm using array foreach to get the value.

foreach($movie as $key=>$value) {
    if($key == 0) {
        echo $_SESSION['movie'] = $value;  //output1
    } else {
        echo $_SESSION['movie'] =  ", ".$value; 
    }   
}

echo $value; //output2

When it echo for output1:

movie1,movie2,movie3

When output 2:

movie3

I would like to use the variable $value outside of foreach but I can't get output1 result, and get only output2 result.

My desired output2:

movie1,movie2,movie3

4
  • push the values into an array then use them outside the for loop block. Commented Apr 17, 2018 at 16:37
  • You need to append the values to your $value variable atm you assign it to $_SESSION['movie']. Commented Apr 17, 2018 at 16:40
  • implode(',', $movie) Commented Apr 17, 2018 at 16:40
  • thank you so much @AlexHowansky ! it works like a charm, didn't know it would be that simple. Thanks!!!! Commented Apr 17, 2018 at 16:43

3 Answers 3

5

If you're iterating the $movie array just to print the movies as a comma separated string, you don't need to.

echo implode(',', $movie);
Sign up to request clarification or add additional context in comments.

1 Comment

And here is the documentation
0

Assign your values to array inside foreach.

foreach($movie as $key=>$value){
 $moviename[]=$value;
 }

Comments

0

Are you trying to store the string in $_SESSION['movie']? Looks like you are confusing yourself a bit there.

foreach($movie as $key=>$value){
    if($key === 0){
        $_SESSION['movie'] = $value; 
    }else{
        $_SESSION['movie'] .=  ", ".$value; 
    }   
}
echo $_SESSION['movie']; //output2

Will result in

Movie1,Movie2,Movie3

You could just use implode. https://secure.php.net/manual/en/function.implode.php eg:

$movie = array(0 => 'Movie1', 1 => 'Movie2', 2 => 'Movie3');
$movie_str = implode(',', $movie);
echo movie_str;

Will result in

Movie1,Movie2,Movie3

2 Comments

yup :) I'm storing it into session
I would just remove the foreach and change my code to: $_SESSION['movie'] = implode(',', $movie);

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.