Can I use array_push on a SESSION array in php?

别等时光非礼了梦想. 提交于 2019-12-17 06:45:53

问题


I have an array that I want on multiple pages, so I made it a SESSION array. I want to add a series of names and then on another page, I want to be able to use a foreach loop to echo out all the names in that array.

This is the session:

$_SESSION['names']

I want to add a series of names to that array using array_push like this:

array_push($_SESSION['names'],$name);

I am getting this error:

array_push() [function.array-push]: First argument should be an array

Can I use array_push to put multiple values into that array? Or perhaps there is a better, more efficient way of doing what I am trying to achieve?


回答1:


Yes, you can. But First argument should be an array.

So, you must do it this way

$_SESSION['names'] = array();
array_push($_SESSION['names'],$name);

Personally I never use array_push as I see no sense in this function. And I just use

$_SESSION['names'][] = $name;



回答2:


Try with

if (!isset($_SESSION['names'])) {
    $_SESSION['names'] = array();
}
array_push($_SESSION['names'],$name);



回答3:


 $_SESSION['total_elements']=array();
 array_push($_SESSION['total_elements'], $_POST["username"]);



回答4:


Try this, it's going to work :

session_start();

if(!isset($_POST["submit"]))
{
    $_SESSION["abc"] = array("C", "C++", "JAVA", "C#", "PHP");
}

if(isset($_POST["submit"]))
{
    $aa = $_POST['text1'];

    array_push($_SESSION["abc"], $aa);

    foreach($_SESSION["abc"] as $key => $val)
    { 
        echo $val;
    }
}



回答5:


<?php
session_start();

$_SESSION['data']= array();
$details1=array('pappu','10');
$details2=array('tippu','12');

array_push($_SESSION['data'],$details1);
array_push($_SESSION['data'],$details2);

foreach ($_SESSION['data'] as $eacharray) 
{
 while (list(, $value) = each ($eacharray)) 
    {
        echo "Value: $value<br>\n";
    }
}
?>

output

Value: pappu
Value: 10
Value: tippu
Value: 12



来源:https://stackoverflow.com/questions/2616540/can-i-use-array-push-on-a-session-array-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!