counting odd numbers in a database?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
fnsnoop
Forum Newbie
Posts: 1
Joined: Sat Jan 29, 2005 6:58 pm

counting odd numbers in a database?

Post by fnsnoop »

Hi,
I have a database of numbers. I know how to check if it is an odd number. I just don't know how to check how many are in a row from the begining. I want to pull out odd numbers in a row and output how many are in a row till there is a even number. example:

45 - 67 - 71 - 10 - 23 - 44 3 in a row

note it will only pull out the first odd ones and stop completly so this would produce 0 in a row
10 - 29 - 2 - 99 - 37 0 in a row

this would produce the result 1

1 - 18 - 68- 29 - 82 1 in a row

I have tryed doing this for a while but i cant get it to work.

Alex
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

this is probably done better with php doing the "in a row" checks..
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Post by John Cartwright »

You would most likely need to explode the whole string, which would look something like

Code: Select all

$numbers = explode(' - ',$rowї'numbers']);
You will then need to loop through the results checking for your odd number. Odd numbers are generally found using the modulos operation (%)

Code: Select all

$odd = array();
$break = false;

foreach ($numbers as $number)
{
     if (($number % 2 == 1 && !$break)
          $oddї] = $number;
          //you can just increment a value if you do not need to actually store the numbers

     else
          $break = true;
}
now this will build an array ($odd) and it will break once an even number is hit. Now we have to process our results.

Code: Select all

echo 'There are '.count($odd).' odd numbers in this row.';
and if you want to display them

Code: Select all

echo 'They are: ';

foreach ($odd as $oddnum)
{
     echo $oddnum.', ';
}
Post Reply