...

View Full Version : Count elements in an array



Mayhem30
01-16-2010, 08:16 PM
I'm trying to count how many elements are in an array - I've tried to use "count()" and other methods but they just don't work (always returns 1)

The only way I can get it to count it right is by doing this :



$exclude = $vbulletin->db->query_read("SELECT threadid FROM " . TABLE_PREFIX . "thread WHERE visible=1 $excluded_forums_query LIMIT 0,".$howmany_latestposts."");

while ($value = $vbulletin->db->fetch_array($exclude))
{
$pcount++;
}
echo "$pcount";


That echo's "5" which is correct.

My question is - how do I take that variable and include it in my next "while" loop? When I try to use it in my "while" loop, the variable is blank. Outside of the loop, it echos "5" just fine.

Here is my whole script :





// query the database and collect which "threads" we are allowed to read

$exclude = $vbulletin->db->query_read("SELECT threadid FROM " . TABLE_PREFIX . "thread WHERE visible=1 $excluded_forums_query LIMIT 0,".$howmany_latestposts."");

while ($value = $vbulletin->db->fetch_array($exclude))
{
$pcount++;
}


// build a string of the allowed threads and inject it into the mysql query string at the bottom of the code.

while ($value = $vbulletin->db->fetch_array($exclude))
{
$qcount++;
if ($qcount < $pcount)
{
$id .= "threadid=$value[threadid] or ";
}
else
{
$id .= "threadid=$value[threadid]";
}
}

// What happens here is that the string ends with "Threadid=15 or" because the variable $pcount is blank in that while loop.

$latestposts = $vbulletin->db->query_read("SELECT * FROM " . TABLE_PREFIX . "post WHERE $id ORDER BY postid DESC LIMIT 0,".$howmany_latestposts."");

Anyone know how to solve this issue?

ninnypants
01-16-2010, 09:21 PM
You could use the classes equivalent of mysql_num_rows to get the number of row returned by the query. Then you wouldn't have to use the first while loop.

You may also want to initialize you $pcount and $qcount variables outside of the loops and set them to 0 so that if someone else reads your code they aren't wondering where the variables magically appeared from.

Mayhem30
01-16-2010, 10:11 PM
You could use the classes equivalent of mysql_num_rows to get the number of row returned by the query. Then you wouldn't have to use the first while loop.

You may also want to initialize you $pcount and $qcount variables outside of the loops and set them to 0 so that if someone else reads your code they aren't wondering where the variables magically appeared from.

Thank you! The mysql_num_rows + get rid of the "while" loop did the trick!

:thumbsup:



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum