1

I want to push array into existing session array. I would like to use get[id] and I want to be able stack all the arrays added rather than delete them when a new array is pushed.

Bellow is my code and I am not getting the value, instead I get this error --- Array to string conversion. Thanks in advance.

**CODE
  <?php
session_start();

if(empty($_SESSION['animals']))
{
$_SESSION['animals']=array();

}


// push array 
array_push($_SESSION['animals'],  array ( 'id' => "".$_GET['id'].""));

 foreach($_SESSION['animals'] as $key=>$value)
 {   

    // and print out the values

    echo $key; 
    echo $value;
    }
?>
3
  • In which line do you get the error? Commented Nov 16, 2015 at 14:46
  • echo $value; is the error Commented Nov 16, 2015 at 14:48
  • You can run the code easily using the code I posted. there are no additional pages need for it Commented Nov 16, 2015 at 14:49

1 Answer 1

1

With your code, this is what $_SESSION looks like:

array (size=1)
  'animals' => 
    array (size=1)
      0 => 
        array (size=1)
          'id' => string 'test' (length=4)

In your code :

foreach($_SESSION['animals'] as $key=>$value)

key will contain 0 and value will contain array('id' => 'test'). Since value is an array, you cannot echo it like this.

If you want to echo all the characteristics of each animal, this code will work :

<?php
session_start();

if(empty($_SESSION['animals']))
{
    $_SESSION['animals'] = array();
}

// push array 
array_push($_SESSION['animals'],  array ( 'id' => "".$_GET['id'].""));

// We go through each animal
foreach($_SESSION['animals'] as $key=>$animal)
{   
    echo 'Animal n°'.$key; 
    // Inside each animal, go through each attibute
    foreach ($animal as $attribute => $value)
    {
        echo $attribute;
        echo $value;

    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

YES! thanks Heru-Luin-- it works. Just one question, why is the key still starting from 0? i thought it will be replaced by the id?
Because the 'id' => 1 has a key of id and a value of 1
Because with array_push, you append an array to an array. If you want to remove the [0], use $_SESSION['animals']['id'] = $_GET['id'].""; instead of the array_push. Then, your original code will work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.