开发者

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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜