从数组foreach PHP获取变量值

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

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);

Assign your values to array inside foreach.

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

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