0

I am trying to convert a user/pass txt file to an array, I tried to do this with a foreach, explode, reg_split, but didn't get anything working in the right way.

Also a blank line should be skipped...

Example text file:

username1
password1
username2
password2

username3
password4

Example array:

array(
   $username1 => $password1,
   $username2 => $password2
)
bishop
  • 37,830
  • 11
  • 104
  • 139

3 Answers3

3

Create an array of pairs from the consecutive lines, then combine the column of keys with the column of values:

$chunks = array_chunk(
    file('userpass.txt', FILE_SKIP_EMPTY_LINES|FILE_IGNORE_NEW_LINES),
    2
);
$users = array_combine(
    array_column($chunks, 0),
    array_column($chunks, 1)
);

Explanation

$chunks is an array of arrays: each inner array has two elements: #0 is the username (first line) and #1 is the password (second line). Using file to skip blank lines and remove trailing new-lines keeps this code simple, but not bullet-proof.

$users then is made by taking all the usernames (index 0 from all the inner arrays) and pointing them to all the passwords (index 1).

You can accomplish the same with a loop over $chunks. However, I prefer this approach because all looping is handled inside the engine, where it is marginally more performant.

bishop
  • 37,830
  • 11
  • 104
  • 139
1

Split the file into one array and then combine them into a new array with key-value pairs

$file = file("usernames.txt", FILE_SKIP_EMPTY_LINES|FILE_IGNORE_NEW_LINES);
$array = [];

for($i = 0; $i < count($file) - 1; $i++){
  $array[$file[$i]] = $file[$i + 1];
}
spencer.sm
  • 19,173
  • 10
  • 77
  • 88
-3

I have to think on it, but I know you can read the file into an array using php's file() method.

$var = file("myFile.txt", FILE_SKIP_EMPTY_LINES);
VikingBlooded
  • 884
  • 1
  • 6
  • 17