Foreach problem

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View
I have the following issue:

I read lines of information from a log file. Each line is identified by an
ID number.
Due to nature of the logging process it is possible blocks are logged more
than once, but in these cases the IDs will be similar.
In my PHP script I temporarily store all read ID numbers in an array. When
done reading  I want to sort the array and then loop through it to check for
doubles. Right now all I am interested in is knowing how many doubles there

The simple log lines look like this:

33,222,671 string
33,222,814 string

part of my code:

$idarr = array ();
while (!feof ($logfile))
    $line = $gets ($logfile,1024);
    $items = explode (" ",$line);
    $idarr[] = $items[0];    // add the id to an array ( I guess as a
    // rest of code, irrelevant to issue
$idarr = sort ($idarr); // make sure doubles are in consecutive order
$tempid = "";
$doubles = 0;
foreach ($idarr as $id)
    if ($id == $tempid)  // evals to true when this id is same as the one
before this
        $doubles++; // which means we have found another double
    $tempid = $id;
echo $doubles;

The code runs until it hits the foreach, then it returns a warning:
Warning: Invalid argument supplied for foreach() in
/srv/www/htdocs/area51/script.php on line 315
The $doubles value echoed to the screen is 0

Can anyone point out where I am wrong here ? I know the code isn't exactly
rocket science, but hey, we all have to start somewhere!


Re: Foreach problem


I would check the array with count($idarr) because the error yu are getting
could be the result of an empty array in which case you will need to look at
the wasy you are parsing the file.



Quoted text here. Click to load it

Re: Foreach problem

jerrygarciuh wrote:
Quoted text here. Click to load it
Thanks Jerry! The problem was the sort (). Sort does not return an array but
true or false (1, 0)
So I changed:

$idarr = sort ($idarr);
sort ($idarr);

That did it!  Your tip to echo count ($idarr)  was a great help!
It runs smoothly now!
Thanks again!

Site Timeline