We're a community of 1076K IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,075,820 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion

how to create an array of posted usernames & passwords

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.

2
Contributors
1
Reply
1 Hour
Discussion Span
1 Year Ago
Last Updated
2
Views
spowel4
Junior Poster in Training
54 posts since Jul 2008
Reputation Points: 10
Solved Threads: 0
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.

shovels
Newbie Poster
12 posts since Sep 2007
Reputation Points: 10
Solved Threads: 1
Skill Endorsements: 0

This article has been dead for over three months: Start a new discussion instead

Post: Markdown Syntax: Formatting Help
 
You
View similar articles that have also been tagged:
 
© 2013 DaniWeb® LLC
Page rendered in 0.0719 seconds using 2.67MB