Hello.
I’m a newbie to PHP..
I have a problem that asks for me to [I]create a program that reads a file that has a list of emails and the program counts the number of times an email is repeated, then write the emails and the number of times it was repeated to another file line by line in ascending order based on the number of times each email was repeated (using arsort()).
Now, my solution was to run a double loop and save the email and the number of times it was repeated to an array as an associative array.
Like so..
[code=php]
[U]addresses.txt[/U]
“[email protected]”
…
…
[U]code[/U]
<?php
$file_access=fopen(“address.txt”, rb);
if (!$file_access){print “some error message:$php_errormsg”;}
else
{
for ($line=fgets($file_access); !feof($file_access); $line=fgets($file_access))
{
$count=0;
if ($line===false){print “some error message:$php_errormsg”;}
else
{
for ($i=fgets($file_access); !feof($file_access); $i=fgets($file_access))
{
if ($line==$i) {$count++;}
}
$email_array=array(’email’ -> $line,
‘count’ -> $count);
}
}
…some rest of code
Well, the book answer says…
[code=php]
<?php
$in_fh = fopen(‘address.txt’, ‘rb’);
if (! $in_fh){
die(“can’t open addresses.txt:$php_errormsg”);
}
$addresses=array();
for ($line = fgets($in_fh); ! feof($in_fh); $line = fgets($in_fh)) {
if ($line === false){
die(“Error reading line:$php_errormsg”);
} else {
$line = trim($line);
$addresses[$line] = $addresses[$line]+1;
}
}
if (! fclose($in_fh)) {
die(“Can’t close addresses.txt:$php_errormsg”);
}
..some rest of code…
I don’t understand this line[I] $addresses[$line] = $addresses[$line]+1;
The book’s explanation for was: [I][COLOR=”Purple”]Use the address as the key in $addresses and the value is the number of times that the address has appeared
How can the line in red evaluate to [COLOR=”Purple”]$addresses[$foo_email]=3