Re: % Help

From: Date: Wed, 21 Feb 2001 05:48:43 +0000
Subject: Re: % Help
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-40891@lists.php.net to get a copy of this message
From: "Jeff Lacy" <jeffdl@mn.mediaone.net> > Hello Everyone, > > Could someone please explain the whole % thing? I sort of understand it, > but not quite. My goal is to have a table, and have every row alternate > between 4 colors. I can alternate sort of alternate between 3, but not > quite. I have tried lots of different combinations, but I can't figure it > out. Thank you very much! % is the modulus operator, it tells you the remainder after dividing two numbers. For example, 5 % 4 will give you the remainder after 5 / 4, which is 1. A common use for this is to check if a number is even or odd, by doing modulus 2. E.g. <? function even_or_odd($number) { if ($number % 2) // if remainder is not 0 { return "odd"; } else // remainder is 0 { return "even"; } } echo even_or_odd(4); // even echo even_or_odd(13); // odd ?> A practical application of that is inside a for-loop you increment a number and return a different colour value depending on whether it's even or odd, to give e.g. each row of a table an alternating background colour. In your case if you want to alternate between four colours, all you need to do is change to modulus 4 instead of modulus 2, i.e. $number % 4, and then check if the remainder is 0, 1, 2 or 3. > > > Maybe there should be a better link to it in the manual. The only one I > could find was at http://www.php.net/manual/en/ref.math.php, > but it is far > from clear (to me at least....). > Well, this is a mathematical concept rather than PHP language-specific. :) Cheers Simon Garner

« previous php.general (#40891) next »