Siddhesh Patil Siddhesh Patil - 21 days ago 6
PHP Question

Unexpected output in PHP Post form

This is my index.php:

<?php
$about_me = array("Lorem ipsum dolor sit amet.",
"Lorem ipsum dolor sit amet", "Lorem ipsum");
?>
<form action="generate.php" method="POST">
<input type="hidden" name="about_me" value="<?php echo $about_me;?>">
<input type="submit" class="download_button" value="download">
</form>


This is generate.php:

<?php
$about_me = $_POST['about_me'];
$test = $about_me[0];
echo $test;
?>


The output of generate.php is

<


I expect the output to be Lorem ipsum dolor sit amet..
But unexpectedly I am recieving just a arrow.
If someone can help me, I will be grateful.

Answer

You cannot echo an array without an index.

So try this instead

<input type="hidden" name="name" value="<?php echo $about_me[0];?>">
//----------------------------------------------------------^^^

Also as you call this input field name i.e. name="name" use its name here

<?php
$about_me = $_POST['name'];
echo $about_me;
?>

But remember this will only pass the first occurance of the index.php's $about_me array.

If you want to pass all the data you added to the $about_me array, instead make it a simple string

<?php
$about_me = "Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet,Lorem ipsum"
?>
<form action="generate.php" method="POST">
<input type="hidden" name="about_me" value="<?php echo $about_me;?>">
<input type="submit" class="download_button" value="download">
</form>

Or create as many hidden fields as there are occurances in your array

<?php
$about_me = array("Lorem ipsum dolor sit amet.",
                  "Lorem ipsum dolor sit amet", 
                  "Lorem ipsum");
?>
<form action="generate.php" method="POST">
<?php
foreach ( $about_me as $me) :
?>
    <input type="hidden" name="about_me[]" value="<?php echo $me;?>">
<?php
endforeach;
?>
<input type="submit" class="download_button" value="download">
</form>

And then process like this

<?php
    if (isset($_POST['about_me']) {
        foreach ($_POST['about_me'] as $me) {
            echo $me . '<br>';
        }
    } else {
        echo 'Woops no data found';
?>
Comments