heisenberg
heisenberg

Reputation: 1954

Obtaining $_SESSION array values and displaying using echo

I have the ff code which stores values inputted in form's textfield to a session array which I named "numbers". I need to display the value of the array but everytime I try echo $value; I get an error Array to string conversion in

I used echo var_dump($value); and verified that all the inputted values are stored to the session array.

My goal is to store the user input to an array everytime the user hits the submit button.

How do I correct this?

<?php 
    session_start();
?>

<html>
<head>
    <title></title>
</head>
<body>
    <form method="POST" action="index.php"> 
        <label>Enter a number</label>&nbsp;
        <input type="text" name="num" required />
         <button type="submit">Submit</button> 
    </form>
</body>
</html>

    <?php
    if (isset($_POST["num"]) && !empty($_POST["num"])){
        $_SESSION['numbers'][] = $_POST["num"];

        foreach($_SESSION as $key => $value){
            echo ($value);
        }
    }
    ?>

Thank you.

Upvotes: 0

Views: 46

Answers (3)

kiks73
kiks73

Reputation: 3758

If you want to echo all entered numbers, your for each cycle should be:

foreach($_SESSION[‘numbers’] as $key => $value) {
    echo $value;
}

This is because the $_SESSION[‘numbers’] itself is the array that contains the numbers.

Upvotes: 0

Emile P.
Emile P.

Reputation: 3962

When doing $_SESSION['numbers'][] = $_POST["num"];, you are making $_SESSION['numbers'] an array: so you'll either need to do that differently, or check whether $value within your foreach loop is an array or not.

if (isset($_POST["num"]) && !empty($_POST["num"])){
    $_SESSION['numbers'][] = $_POST["num"];

    foreach($_SESSION as $key => $value){
        if (is_array($value)) {
            foreach ($value as $valueNested) {
                echo ($valueNested);
            }
        } else {
            echo ($value);
        }
    }
}

OR

if (isset($_POST["num"]) && !empty($_POST["num"])){
    $_SESSION['numbers'] = $_POST["num"];

    foreach($_SESSION as $key => $value){
        echo ($value);
    }
}

The latter is probably what you are actually trying to accomplish.

Upvotes: 1

Daniel Tran
Daniel Tran

Reputation: 6171

The error is because SESSION[“numbers”] is an array and you can just echo an array. It will throw an error “Array to string converstion”.

Iterate through the array and print it instead.

Upvotes: 0

Related Questions