Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    New Coder
    Join Date
    May 2006
    Posts
    15
    Thanks
    0
    Thanked 0 Times in 0 Posts

    incrementing a variable

    I don't know what this is called in order to referece it. Basically I see that you can do a loop to automatically increment a variable (not the value of a variable) like this:

    Code:
    $var1 = "line 1<br>";
    $var2 = "line 2<br>";
    for ( $i = 1; $i <= 40; $i++) {
      echo ${'var'.$i};
    }
    What I don't know if it's possible is to do that with a $_POST. For example after a person submits a form with 40 fields, it sends to $_POST['field1'] and so on to 40. Instead of echoing every $_POST or manually assigning it an intermediate variable, I'd just like to do an incremental loop with the $_POSTs for the handling.

    1. What is the ${'var'.$i} concept called?
    2. How would this work with $_POST?

  • #2
    met
    met is offline
    Regular Coder
    Join Date
    Oct 2009
    Location
    United Kingdom
    Posts
    728
    Thanks
    4
    Thanked 119 Times in 119 Posts
    with regards to curly bracers and echoing ~ http://www.nusphere.com/kb/phpmanual...arsing.complex

    with regards to post and lots of fields ~ http://php.net/manual/en/control-structures.foreach.php

  • #3
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,987
    Thanks
    4
    Thanked 2,660 Times in 2,629 Posts
    Use an array; that will let you control the size of the variables:
    Code:
    <input type="text" name="field[1]" />
    <input type="text" name="field[2]" />
    ...
    PHP Code:
    foreach ($_POST['field'] AS $key => $value)
    {
        
    printf("Field offset: %d = %s\n"$key$value);
    }

    // Or:
    $iFieldCount count($_POST['field']);
    for (
    $i 0$i $iFieldCount; ++$i)
    {
        
    printf("Field offset: %d = %s\n"$i$_POST['field'][$i]);

    In response to you're first question, thats called concatination of strings to be interpreted later as a variable. This is IMO a bad approach. Arrays are much more simplistic and easy to go. $_POST itself can be completely iterated and evaluated on an individual level for each key / value combinations. Above code shows if you were to group a particular part as an array, which would make sense for things like radio buttons, potentially password verifications, user bio information, and whatnots.
    PHP Code:
    header('HTTP/1.1 420 Enhance Your Calm'); 


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •