0

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);


?>

3 Answers 3

3

You're assigning $_POST["travel"], which is not an array but a string, to $travel. Turn it into an array first.

Sign up to request clarification or add additional context in comments.

1 Comment

hm.. actually $_POST["travel"] is an array, if you're using name="travel[]"
1

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);
?>

Comments

0

$_POST is an array, $_POST['travel'] however is just an element unless its originating from a multiselect element.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.