Question

<?php
    session_start();    
    $_SESSION['del']=array("a1","a2","a3","a4","a5");
    unset($_SESSION['del'][0]);
    echo implode(" ",$_SESSION['del'])    
?>

How do I remove each array element one by one every time I refresh the page?

Was it helpful?

Solution

here is the code

<?php
session_start();    
if(isset($_SESSION['del'])) {  // to make sure array is not set again as in question
    unset($_SESSION['del'][0]); // remove the first element
    $_SESSION['del'] = array_values($_SESSION['del']); // to shift rest of the elements one location left for making indexes starts from 0
} else { // set session array only once
    $_SESSION['del']=array("a1","a2","a3","a4","a5");
}
echo implode(" ",$_SESSION['del']); // print results    
?>

OTHER TIPS

if(isset($_SESSION['del']))
{
 if(is_array($_SESSION['del']))
 {
  array_shift($_SESSION['del']);
 }
}

Code Explanation

if the session del is currently set.

and that the session['del'] is an array

remove the first value of the array del.

I am not sure if it works with $_SESSION, but if it is an array then array_shift() would be what you are looking for:

array_shift($_SESSION['del']);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top