Pables Pables - 7 months ago 39
PHP Question

Save each username and password into an array

I have a text file with the following



and would like each username and password to be saved into the same array so that it looks like this

[0] = > username

[1] = > password

[2] = > admin

[3] = > admin123

This is my code currently:

$accounts = file("password.txt");

foreach($accounts as $account) {
$user = preg_split("/,/", $account ) ;

print_r( array_values( $user ));

It seems to only saves each line into the array and then overwrite it with the next username and password.

Clarification: This is for a beginner PHP course, not for an actual site. I know passwords are never supposed to be stored in plaintext...

kb. kb.

Make $user an array and append values to it using [] notation.

$accounts = file("password.txt");
$user = array();
foreach($accounts as $account) {
    list($name, $pass) = preg_split("/,/", $account ); 
    $user[] = $name;
    $user[] = $pass;
    // Or use array_push($user, preg_split("/,/", $account ));
print_r( array_values( $user ));

Clarification: To set a specific key in an array the syntax is $var["key"], by omitting the key argument PHP treats $var[] as an append/push and appends the value to the end of the array $var.