How do I add data from a PHP form into an array?

2019-06-04 22:18发布

问题:

If I have a loop that requests my data from my form:

for ($i=0;$i < count($_POST['checkbx']);$i++) {
    // calculate the file from the checkbx
    $filename = $_POST['checkbx'][$i];
    $clearfilename = substr($filename, strrpos ($filename, "/") + 1);
    echo "'".$filename."',";       
}

How do I add that into the sample array below?:

$files = array(
  'files.extension',
  'files.extension', 
);

回答1:

Even smaller:

$files = array();
foreach($_POST['checkbx'] as $file)
{
    $files[] = basename($file);
}

If you aren't absolutely sure that $_POST['checkbx'] exists and is an array you should prolly do:

$files = array();
if (is_array(@$_POST['checkbx']))
{
    foreach($_POST['checkbx'] as $file)
    {
        $files[] = basename($file);
    }
}


回答2:

Remember that you also need to name these checkboxes in HTML with "[]" after their names. e.g.:

<input type="checkbox" name="checkbx[]"  ...etc... >

You will then be able to access them thusly:

<?php

// This will loop through all the checkbox values
for ($i = 0; $i < count($_POST['checkbx']); $i++) {
   // Do something here with $_POST['checkbx'][$i]
}

?>


回答3:

$files[] =$filename;

OR

array_push($files, $filename);


回答4:

You can use the array_push function :

<?php
$stack = array("orange", "banana");
array_push($stack, "apple", "raspberry");
print_r($stack);
?>

Will give :

Array
(
    [0] => orange
    [1] => banana
    [2] => apple
    [3] => raspberry
)

Simply fill the array using array_push for each file.



回答5:

Probably like this:

for ($i=0;$i < count($_POST['checkbx']);$i++) {
// calculate the file from the checkbx
$filename = $_POST['checkbx'][$i];
$clearfilename = substr($filename, strrpos ($filename, "/") + 1);

$files[] = $filename; // of $clearfilename if that's what you wanting the in the array  
}


回答6:

I'm not entirely sure what you want to add to that array, but here is the general method of 'pushing' data into an array using php:

<?php
$array[] = $var;
?>

for example you could do:

for ($i=0;$i < count($_POST['checkbx']);$i++)
{
   // calculate the file from the checkbx
   $filename = $_POST['checkbx'][$i];
   $clearfilename = substr($filename, strrpos ($filename, "/") + 1);

   echo "'".$filename."',";       
   $files[] = $filename;
}