0

Hello, all. Please advise how to use $_POST in cycle. I have the following code:

  1. <?php
  2. if (isset($_POST['id1'])) {$id1 = $_POST['id1']}
  3. if (isset($_POST['id2'])) {$id2 = $_POST['id2']}
  4. if (isset($_POST['id3'])) {$id3 = $_POST['id3']}
  5. ?>

I have tried:

  1. <?php
  2. for ($x=1, $x<=3, $x++)
  3. {
  4. if (isset($_POST['id".$x."'])) {$id".$x." = $_POST['id".$x."'];}
  5. }
  6. ?>

...but it doesn't work. :(

3
Contributors
2
Replies
3
Views
5 Years
Discussion Span
Last Post by pritaeas
0

The problem i see is here $id".$x." = $_POST['id".$x."'];

you can't concat a string onto a variable name, you should use an array for that eg.

<?php
$ids = array();
for ($x=1; $x<=3; $x++){
    if (isset($_POST['id'.$x])) {
        $ids[] = $_POST['id'.$x];
    }
}
var_dump($ids);
?>

When you concat you need to make sure you use the same quote the string was started with, when it starts with a single quote it needs to close with another single quote - a double quote will just be put in the string literally and vice versa when it is opened with a double quote and you type a single quote inside it.

You could do something like this below for any number of id fields:

$ids = array();
foreach($_POST as $k=>$v){
    if(substr($k,0,2) == 'id'){
        $ids[] = $v;
    }
}

foreach($ids as $v){
    echo $v."<br/>\r\n";
}
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.