简体   繁体   中英

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">
<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是一个数组,但是$_POST['travel']只是一个元素,除非它源自multiselect元素。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM