简体   繁体   中英

cant push array key and value

I have a page called animal.php that has a list of animal names with a button next to each animal name. When any of the buttons are clicked, the user is sent to showanimal.php where the animal name is displayed as $value and $key is auto incremented. I am displaying it using a foreach loop so that I can display the names of all animals of each animal clicked.

The problem is, I added " size => " to array_push next to the get[id], so that I can set up my own key instead of an auto incremented one. But I am getting an error saying "". syntax error, unexpected '=>' (T_DOUBLE_ARROW) in line 10, which is this line bellow.

LINE 10

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

I have to set a key that is not auto incremented, because I need to update each key later on. How can i fix this problem its frustrating because it works without the push array...

Thanks in advance and bellow is my full code!

animal.php

    <div class="product">
    <h3>BIRD</h3>
    <a href="showanimal.php?id=bird">Add animal</a>
</div>

<div class="product">
    <h3>DOG</h3>
<a href="showanimal.php?id=dog">Add animal</a>
</div>

<div class="product">
    <h3>LION</h3>
    <a href="showanimal.php?id=lion">Add animal</a>
</div>

showanimal.php

    <?php
session_start();

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

// push array using get id as KEY and size as VALUE.
    // getting error on the line bellow " unexpected '=>' (T_DOUBLE_ARROW)"
array_push($_SESSION['animals'],    "size" => "".$_GET['id']."" );

// We go through each animal
foreach($_SESSION['animals'] as $key=>$value)
{   
echo "the key is :::::::: " . $key;
echo "<BR/>";
echo "the value is :::::::: " . $value;
echo "<BR/>";
echo "---------------------------------";
echo "<BR/>";
}
?>

You should try:

$_SESSION['animals']['size'] = $_GET['id'];

or merging

$_SESSION['animals'] = array_merge( $_SESSION['animals'], 
    array( 'size' => $_GET['id'] ) );

or a union

$_SESSION['animals'] += array( 'size' => $_GET['id'] );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM