Jump to content

Archived

This topic is now archived and is closed to further replies.

AncientSage

...variable within an array?

Recommended Posts

Hello,

I'm attempting to contain a variable number within an array, for example...

$array[$x]

$x is a number, the number is sent through a form. However, since I do not know that number, I am unsure of how to put it into the array slot.

$array[$_POST[$x]]

Won't work, perhaps if I pass it via a GET method or something it will work? Or is there another way?

Perhaps it's because $x is no longer in the script once it is executed, $x is in the name element of a form.

My code...

[code]
  $textfile = "filelist.txt";
  if (file_exists($textfile) && is_file($textfile)) {
  $fp = fopen($textfile, "r");
  $file = file_get_contents($textfile, False, NULL);
  $rows = explode("\n", $file);
    if(isset($_POST['checksubmit'])) {
        unset($rows[$x]);
      }
  $x = 0;
  echo "<form action=\"" . append_sid("admin.php") . "\" method=\"POST\">";
      foreach($rows as $row) {
        if($row == ""){
          continue;
        }
      echo "<input type=\"checkbox\" name=\"" . $x . "\">" . $row . "<br /> ";
      $x++;
      }
  echo "<input type=\"hidden\" name=\"checksubmit\">";
  echo "<br /><input type=\"submit\" value=\"Delete Selected\">";
  echo "</form>";
  }
[/code]

Share this post


Link to post
Share on other sites
are you saying you don't know the form element's name?

if you do:

[code]$array["{$_POST['element_name']}"];[/code]

should work just fine.

Share this post


Link to post
Share on other sites
Yes, as seen in my code...
      echo "<input type=\"checkbox\" name=\"" . $x . "\">"

$x is auto-incremented, and there are multiple input fields. I need to somehow find the name attribute out, and then allow it to be accessed by the $_POST global variable.

Share this post


Link to post
Share on other sites
Your code isn't going to work anyway, since the names you are generating are all number and you can't have a variable in PHP which is a number (at least I don't think so). A much better way would be to make the $x an index into an array, such as:
[code]<?php
echo '<input type="checkbox" name="row[' . $x . ']">' . $row . "<br /> ";
?>[/code]
Then in your processing script:
[code]<?php
    if(isset($_POST['checksubmit'])) {
        if(isset($_POST['row']))
          foreach($_POST['row'] as $i)
              unset($rows[$i]);
    }
?>[/code]

Note: untested

Ken

Share this post


Link to post
Share on other sites
just a change to his code to make it work the way he has the PHP written:

[code]<input type="checkbox" name="row[]" value="'. $x .'">[/code]

Share this post


Link to post
Share on other sites

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.