每次重新加载页面时,如何逐个删除数组元素?

时间:2013-09-12 01:30:20

标签: php arrays session unset

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

每次刷新页面时,如何逐个删除每个数组元素?

3 个答案:

答案 0 :(得分:1)

这是代码

<?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    
?>

答案 1 :(得分:1)

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

代码说明

如果当前设置了会话del。

并且会话['del']是一个数组

删除数组del的第一个值。

答案 2 :(得分:0)

我不确定它是否适用于$_SESSION,但如果它是一个数组,那么array_shift()就是你想要的:

array_shift($_SESSION['del']);