Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question

5 Answers 5

up vote 17 down vote accepted

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_pus as I see no sense in this function. And I just use

$_SESSION['names'][] = $name;
share|improve this answer
    
Thanks for the great suggestion! –  zeckdude Apr 11 '10 at 10:13
    
Thank you! This had me stumped for a while as well. –  xbonez Oct 27 '11 at 2:48

Try with

if (!isset($_SESSION['names'])) {
    $_SESSION['names'] = array();
}
array_push($_SESSION['names'],$name);
share|improve this answer
    
Thank you for your help! –  zeckdude Apr 11 '10 at 10:13
 $_SESSION['total_elements']=array();
 array_push($_SESSION['total_elements'], $_POST["username"]);
share|improve this answer
3  
While this code snippet may solve the question, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. –  Bono Mar 10 at 16:18

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;
    }
}
share|improve this answer
<?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

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.