1,105,391 Community Members

how to create an array of posted usernames & passwords

Member Avatar
Junior Poster in Training
72 posts since Jul 2008
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]

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.

Member Avatar
Newbie Poster
12 posts since Sep 2007
Reputation Points: 0 [?]
Q&As Helped to Solve: 1 [?]
Skill Endorsements: 0 [?]

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.

This article has been dead for over three months: Start a new discussion instead
Start New Discussion
View similar articles that have also been tagged: