开发者

Add user input to array

开发者 https://www.devze.com 2023-03-26 21:39 出处:网络
I am trying to add user input to a previously created array with array_merge.However, I am having trouble echoing the entire, new array as an unordered list.the user\'s entry is being processed correc

I am trying to add user input to a previously created array with array_merge. However, I am having trouble echoing the entire, new array as an unordered list. the user's entry is being processed correctly, but the original array is displaying as "Array" within the unordered list. Here is the code:

<?php
$travel = array("Automobile", "Jet", "Ferry", "Subway");

foreach ($travel as $t)
    {
    echo "<开发者_如何学C;ul>";

    echo "<li>$t</li>";

    echo "</ul>";

    }
?>

<form action="arrays.php" method="post">
<input type="text" name="added" />
<?php

foreach ($travel as $t)
{
echo "<input type=\"text\" name=\"travel[]\" value=\"$t\" />";      
}

?>
<input type="submit" name="submit" value="Add More!" />
</form>

<?php

$travel = array($_POST["travel"]);

$added = explode(",", $_POST["added"]);

$travel = array_merge($travel, $added);

echo "<p> Here is the list with your additions:</p>";

echo "<ul>";

foreach ($travel as $t)
{
echo "<li>$t</li>";
}

echo "</ul>";
?>


Try using a new variable name for the new array created by array_merge(). I think you may run into problems modifying the array you're storing into.


$travel = array($_POST["travel"]);

should be

$travel = $_POST['travel'];


The problem was solved thus:

if (isset($_POST["submit"]))
{
$travel = $_POST["travel"];
$added = explode(",", $_POST["added"]);
$travel = array_merge($travel, $added);


echo "<p> Here is the list with your additions:</p>";

echo "<ul>";

foreach ($travel as $t)
    {
    echo "<li>$t</li>";
    }

echo "</ul>";
}
?>
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号