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. :(

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

Within the loop:

$var = 'id' . $x;
$$var = isset($_POST[$var]) ? $_POST[$var] : '';
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.