PHP merging two arrays
I am trying to merge two arrays with array_merge(), but I am receiving the following warning:
Warning: array_merge() [function.array-merge]: Argument #1 is not an array on line 41
Here is the code:
$travel = array("Automobile", "Jet", "Ferry", "Subway");
echo "<ul>";
foreach ($travel as $t)
{
echo "<li>$t</li>";
}
echo "</ul>";
?>
<h4>Add more options (comma separated)</h4>
<form method="post" action="index2.php">
<开发者_StackOverflow中文版;input type="text" name="added" />
<?php
foreach ($travel as $t){
echo "<input type=\"text\" name=\"travel[]\" value=\"$t\" />\n";
}
?>
<input type="submit" name="submit" value="Add" />
</form>
<?php
$travel = $_POST["travel"];
$added = explode(",", $_POST["added"]);
$travel = array_merge($travel, $added);
print_r ($travel);
?>
You're assigning $_POST["travel"]
, which is not an array but a string, to $travel
. Turn it into an array first.
You are accessing $_POST["travel"]
but it's not defined if you didn't submit the form. You need to check if it's a post request:
<?php
if(isset($_POST["travel"])){
$travel = $_POST["travel"];
$added = explode(",", $_POST["added"]);
$travel = array_merge($travel, $added);
}
print_r ($travel);
?>
$_POST
is an array, $_POST['travel']
however is just an element unless its originating from a multiselect element.
精彩评论