PHP merging two arrays - php

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 is an array, $_POST['travel'] however is just an element unless its originating from a multiselect element.

Related

form checkbox value php

I have a form created by a while loop in php like this :
<form action='#' method='post'>
<input type='hidden' name='form_valid' id='form_valid'>
<?php
$i=-1;
$result_array = array();
//the while is from a simple mysql query
while( $line = $results->fetch() )
{
$i++;
echo"<input type='checkbox' class='checkbox' value='".$line->nid."' id='".$i."'>";
echo $line->title;
echo'<br>';
$result_array[$i] = $line->nid;
}
<input type='submit'>
?>
</form>
Then later on the code I'd like to store the values of the checked checkboxes only in a new array :
if (isset($_REQUEST['form_valid'])) //checking is form is submitted
{
foreach($result_array as $result)
{
if($result == $_REQUEST[$j]) <<<< ERROR
{
$final_array[$j] = $result;
}
}
}
Surprisingly, this code does not work at all.
The error message is "Notice : Undefined offset: 0", then offset 1 then 2 etc ...
The line where the message says theres an error is the marked one.
I really have no idea how to do this. Someone ? =)
Don't try to do it this way, this just makes it hard to process, just use a grouping name array: name="checkboxes[<?php echo $i; ?>]", then on the submission, all values that are checked should simply go to $_POST['checkboxes']. Here's the idea:
<!-- form -->
<form action="" method="POST">
<?php while($line = $results->fetch()): ?>
<input type="checkbox" class="checkbox" name="nid[<?php echo $line->nid; ?>]" value="<?php echo $line->nid; ?>" /><?php echo $line->title; ?><br/>
<?php endwhile; ?>
<input type="submit" name="submit" />
PHP that will process the form:
if(isset($_POST['submit'], $_POST['nid'])) {
$ids = $_POST['nid']; // all the selected ids are in here
// the rest of stuff that you want to do with it
}

why does my code echo my post variables but still give me Invalid argument supplied for foreach() warnings?

I get two warnings Warning: Invalid argument supplied for foreach() but I still retrieve my expected post variables. Where am I going wrong? It says the warning is in regard to line 7, which in this case is the line that begins; foreach($value as $k => $v)
<!------------- quote.php ----------------->
<body>
What services are you interested in? <br/><br/>
<form name="input" action="quote2.php" method="post">
<?php
$services = array('Tree Felling', 'Height Reduction', 'Crown Thinning', 'Deadwooding/Ivy Removal', 'Stump Grinding', 'Other');
foreach ($services as $option) { ?>
<input id="<?= $option ?>" type="checkbox" name="services[]" value="<?= $option ?>" />
<label for="<?= $option ?>"><?= $option ?></label>
<br />
<? }
?>
<br/>
<input name="name" type="text" />NAME</br>
<input name="place" type="text"/>TOWN</br/>
<input type="submit" value="Submit">
</form>
</body>
<!------------ quote2.php -------------->
<?php
echo '<h3>SERVICES REQUIRED</h3>';
foreach ($_POST as $key => $value) {
foreach($value as $k => $v)
{
echo '<p>'.$v.'</p>';
}
}
echo "<hr /><h3>DETAILS</h3>";
echo $name = $_POST['name'];
echo "</br>";
echo $place = $_POST['place'];
echo "<hr/>"
?>
A number of the form controls do not have names that end in [] and so are not arrays.
You can't loop over a string.
You should pull out each value of the submitted data individually and only loop over services.
The problem is that there is a very real possibility that not all of the items in your $_POST array will have values of type array; which you are assuming according to the code in quote2.php
A simple is_array() check will ensure that only arrays get iterated over in the foreach, here is the edited file contents:
<!------------ quote2.php -------------->
<?php
echo '<h3>SERVICES REQUIRED</h3>';
foreach ($_POST as $key => $value) {
if (is_array($value)) {
foreach($value as $k => $v)
{
echo '<p>'.$v.'</p>';
}
}
}
echo "<hr /><h3>DETAILS</h3>";
echo $name = $_POST['name'];
echo "</br>";
echo $place = $_POST['place'];
echo "<hr/>"
?>
That should do the trick.
Try wrapping your foreach loop in an if statement to check the array is an array. For example:
if (is_array($services)) {
foreach ($services as $option) {
// Some code
}
}
Although I wouldn't worry too much. This is just a cleaner way of writing your code.

How to print_r $_POST array?

I have following table.
<form method="post" action="test.php">
<input name="id[]" type="text" value="ID1" />
<input name="value[]" type="text" value="Value1" />
<hr />
<input name="id[]" type="text" value="ID2" />
<input name="value[]" type="text" value="Value2" />
<hr />
<input name="id[]" type="text" value="ID3" />
<input name="value[]" type="text" value="Value3" />
<hr />
<input name="id[]" type="text" value="ID4" />
<input name="value[]" type="text" value="Value4" />
<hr />
<input type="submit" />
</form>
And test.php file
<?php
$myarray = array( $_POST);
foreach ($myarray as $key => $value)
{
echo "<p>".$key."</p>";
echo "<p>".$value."</p>";
echo "<hr />";
}
?>
But it is only returning this: <p>0</p><p>Array</p><hr />
What I'm doing wrong?
The foreach loops work just fine, but you can also simply
print_r($_POST);
Or for pretty printing in a browser:
echo "<pre>";
print_r($_POST);
echo "</pre>";
<?php
foreach ($_POST as $key => $value) {
echo '<p>'.$key.'</p>';
foreach($value as $k => $v)
{
echo '<p>'.$k.'</p>';
echo '<p>'.$v.'</p>';
echo '<hr />';
}
}
?>
this will work, your first solution is trying to print array, because your value is an array.
$_POST is already an array, so you don't need to wrap array() around it.
Try this instead:
<?php
for ($i=0;$i<count($_POST['id']);$i++) {
echo "<p>".$_POST['id'][$i]."</p>";
echo "<p>".$_POST['value'][$i]."</p>";
echo "<hr />";
}
?>
NOTE: This works because your id and value arrays are symmetrical. If they had different numbers of elements then you'd need to take a different approach.
You are adding the $_POST array as the first element to $myarray. If you wish to reference it, just do:
$myarray = $_POST;
However, this is probably not necessary, as you can just call it via $_POST in your script.
Why are you wrapping the $_POST array in an array?
You can access your "id" and "value" arrays using the following
// assuming the appropriate isset() checks for $_POST['id'] and $_POST['value']
$ids = $_POST['id'];
$values = $_POST['value'];
foreach ($ids as $idx => $id) {
// ...
}
foreach ($values as $idx => $value) {
// ...
}
Just:
foreach ( $_POST as $key => $value) {
echo "<p>".$key."</p>";
echo "<p>".$value."</p>";
echo "<hr />";
}
Because you have nested arrays, then I actually recommend a recursive approach:
function recurse_into_array( $in, $tabs = "" )
{
foreach( $in as $key => $item )
{
echo $tabs . $key . ' => ';
if( is_array( $item ) )
{
recurse_into_array( $item, $tabs . "\t" );
}
else
{
echo $tabs . "\t" . $key;
}
}
}
recurse_into_array( $_POST );
Came across this 'implode' recently.
May be useful to output arrays. http://in2.php.net/implode
echo 'Variables: ' . implode( ', ', $_POST);
$_POST is an array in itsself you don't need to make an array out of it. What you did is nest the $_POST array inside a new array. This is why you print Array.
Change it to:
foreach ($_POST as $key => $value) {
echo "<p>".$key."</p>";
echo "<p>".$value."</p>";
echo "<hr />";
}
$_POST is already an array. Try this:
foreach ($_POST as $key => $value) {
echo "<p>".$key."</p>";
echo "<p>".$value."</p>";
echo "<hr />";
}
As you need to see the result for testing purpose. The simple and elegant solution is the below code.
echo "<pre>";
print_r($_POST);
echo "</pre>";

Add user input to array

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 "<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>";
}
?>

Why does my php drop down form result in an Undefined offset

Please could you check this code and see why its returning an Undefined offset: and how it can be fixed.
options.php
<?php
$options = array();
$options["PC 1"] = array("year"=>"2000","colour"=>"blue");
$options["PC 2"] = array("year"=>"2003","colour"=>"pink");
$options["PC 3"] = array("year"=>"2006","colour"=>"orange");
?>
index.php
<html>
<body>
<form name="input" action="test.php" method="post">
Device Name: <?php
include("options.php");
echo '<select name="option">';
foreach($options as $name => $values)
{ echo '<option value="' .$name .'">' .$name .'</option>';
}
echo '</select>';
?>
<input type="submit" value="Submit" />
</form>
</body>
</html>
test.php
<?php
include("options.php");
$chosenValue = $_POST['option'];
list($year,$colour) = $options[$chosenValue]; ---- here is the error line
echo $year;
echo $colour;
?>
Thanks
I think it's because the key's in your array $options have spaces in them. Which is completely valid/legal in PHP, but in HTML, when the form is submitted it doesn't like it.
Try changing them to $options["PC1"] and so on and see if it fixes it.
Edit: From the PHP manual - list() only works on numerical arrays and assumes the numerical indices start at 0.
Try changing test.php to:
<?php
include("options.php");
$chosenValue = $_POST['option'];
$year = $options[$chosenValue]['year'];
$colour = $options[$chosenValue]['colour'];
echo $year;
echo $colour;
?>
Change the way you access year and colour in test.php, list() doesn't seem to work well with non-numeric indices. One of the user-contributed comments in the php docs suits your needs
http://www.php.net/manual/en/function.list.php#53420
Or just go for
$data = &$options[$chosenValue];
echo $data['year']; // etc

Categories