Jakie
Jakie

Reputation: 103

push array key and value in associative array

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

Upvotes: 1

Views: 922

Answers (1)

FrancoisBaveye
FrancoisBaveye

Reputation: 1902

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;

    }
}

Upvotes: 1

Related Questions