I'm posting 20 usernames and 20 passwords, they're named username1 ... username20 and then password1 ... password20. In the page that processes the posted values I have an array like this:

$postArray = array(
      ***
      * other values in array
      ***
      $userName1 = $_POST['userName1'];
      $password1 = $_POST['password1'];
      *
      *
      $userName20 = $_POST['userName20'];
      $password20 = $_POST['password20'];
    );

Is there some way I can do a loop that would put each username/password into the array rather than having to type out each one individually? For example, I can do this outside of the array assignment block:

for ($i = 1; $i < 21; $i++) {
        $userName[$i] = $_POST['userName' . $i];
        $password[$i] = $_POST['password' . $i];
      }

but I don't know how to get that to work inside the array assignment block.

You could do something like this... You may need to add some validation, but the best part is that if you create more username/password fields in the form you won't have to change the code - it will just loop through them all

// Initialise the array - beware though, this will empty the array if you've already done so.
$arrUsers = array();
// Loop through each of the post values
foreach($_POST as $value) {
  // If the post element has 'username' in
  if(strstr($value, 'username')) {
    // Extract the ID
    $id = substr($value, 8);

    // Set the array values for username and password
    $arrUsers[]['username' . $id] = $_POST['username' . $id];
    $arrUsers[]['password' . $id] = $_POST['password' . $id];
  }
}

I haven't tested this, but it should work. Let me know if you have any problems.

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.