简体   繁体   中英

php foreach in foreach looping

I want to extrect all usernames and passwords each from his file and output it nicely. I wrote a code on my appserv 2.5.1 on my computer but only the last loop gave the username output. Tested the code on other machines and it worked perfectly. Dont know what is the problem ...

usernames.txt content :

user1
user2
user3

passwords.txt content :

pass1
pass2
pass3

script content :

$usernames = explode("\n", file_get_contents("usernames.txt"));
$passwords = explode("\n", file_get_contents("passwords.txt"));

foreach( $usernames as $username )
{
    foreach( $passwords as $password )
    {
        echo $username.":".$password."\n";
    }
}

output :

:pass1
:pass2
:pass3
:pass1
:pass2
:pass3
user3:pass1
user3:pass2
user3:pass3
for ($i=0;$i<count($usernames) && $i<count($password); $i++) {
    echo $usernames[$i].':'.$passwords[$i];
}

But $password[x] must be related to $usernames[x]

After debugging with the post author, I guessed that the problem was with the line return character. Using a \\r\\n fixed the problem:

$usernames = explode("\n\r", file_get_contents("usernames.txt"));
$passwords = explode("\n\r", file_get_contents("passwords.txt"));

For reference, please note that it is very important not to assume your input data is right. If you see that something is wrong and it points obviously to a mistake you made previously (in that case it is clearly not the foreach function that is buggy, but the array), then you need to swallow your pride and debug your own code. I have been programming PHP for 10 years, and I still have to remember that every single day.

There's always those that will say you don't need it (and you often don't) but I tend to use regular expressions whenever I'm parsing these kind of flat files - there's always some quirky character, extra line-break or difference that finds it's way into a text file - be it from transferring servers, restoring backups or simply user-interference. You could also make use of array_combine in this situation if you'd prefer to carrying on using a foreach loop - I know some folks prefer it for readability.

preg_match_all('/\w+/m', file_get_contents('usernames.txt'), $usernames);
preg_match_all('/\w+/m', file_get_contents('passwords.txt'), $passwords);

if(count($usernames[0]) !== count($passwords[0]))
    die('Computer says: mismatch!');  // some resemblance of error handling...

$result = array_combine($usernames[0], $passwords[0]);
foreach($result as $name => $pass)
    echo "{$name}:{$pass}\n";

demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM