Skip to page content or skip to Accesskey List.
Search evolt.org
evolt.org login: or register

Work

Main Page Content

Web Scripting and Logic, or Boolean Algebra

Rated 4.16 (Ratings: 4) (Add your rating)

Log in to add a comment
(9 comments so far)

Want more?

 
Picture of spinhead

Joel D Canfield

Member info | Full bio

User since: April 18, 2001

Last login: March 01, 2008

Articles written: 7

Most search engines offer at least four ways to perform your search. Enter a few words, and then select

  • Any of these words
  • All of these words
  • This exact phrase
  • Boolean search

The first three are pretty easy to figure out. The fourth, if you're familiar with computer programming, should be easy to figure out. But if you're new to web design or just beginning to venture into more complex coding involving scripting languages like JavaScript or VBScript (used to create Active Server Pages) you'll benefit from a basic understanding of this Boolean thing.

This article isn't intended to be an exhaustive discussion of the rules of logic, but rather, an introduction to to the terminology and concepts necessary to include logic in your web applications, for instance, in your form validation. I'll also explain why the other choices in our Internet search above are also Boolean.

Who Was Boole and Was He Really Logical?

George Boole was a British mathematician who lived during the 19th century. Despite Boole's never having a formal university education, he showed such insight in mathematics that, at the age of 34 he was appointed to the chair of mathematics at Queens College, Cork, Ireland where he taught for the rest of his life, earning a reputation as an outstanding educator.

At the age of 39 Boole published "An investigation into the Laws of Thought, on Which are founded the Mathematical Theories of Logic and Probabilities" in which he introduced 'Boolean algebra.' In it he reduced the concepts of logic to a simple algebra, mimicking the algebraic functions of mathematics. This work provided the fundaments of the field of logic, and the basis of electronic circuits and computer function.

Application of Logic

In building web applications, once we accept input from outside sources (visitors or other applications) we probably want to verify that input. This frequently requires verifying whether certain input matches one or more criteria, or ensuring that it does not match one or more criteria.

For instance: Does the e-mail address the user provided seem to be well-formed? Do we ship to this zip code? Is this user authorized to access that information?

Strange Math

Matching only one condition is simple; if the condition is true, the statement is true, if the condition is false, it's false. It's when we get into multiple conditions that logic becomes slightly more complex.

Remember memorizing your multiplication tables? You could figure out that 11 x 11 = 121, but it's easier to memorize it. Boolean algebra, or logic, can be boiled down to the simplicity of memorized tables as well. Don't worry; I'll explain it in plain English, too.

Although there are many types of logical functions (with odd names like NAND and XOR), in our elementary scripting, we'll most likely use only AND and OR. The tables below show the logical results of two conditions which can be either TRUE or FALSE, and the results when we connect them using AND and OR.

AND Condition 1
is TRUE
Condition 1
is FALSE
Condition 2
is TRUE
RESULT
is TRUE
RESULT
is FALSE
Condition 2
is FALSE
RESULT
is FALSE
RESULT
is FALSE
 
OR Condition 1
is TRUE
Condition 1
is FALSE
Condition 2
is TRUE
RESULT
is TRUE
RESULT
is TRUE
Condition 2
is FALSE
RESULT
is TRUE
RESULT
is FALSE

Reading the Tables

So what does it all mean? First, we'll translate the tables into English. Then, we'll see how they would apply in a simplified real–world situation.

The AND table illustrates the fact that, when we ask "Does the input match Condition 1 AND Condition 2?" the only time the answer is 'yes' is if both Condition 1 and Condition 2 are true. If either one is false, our answer is 'no'; that is, the whole statement is false. AND functions result in fewer qualifying responses.

The OR table shows that, when we ask "Does the input match Condition 1 OR Condition 2?" the answer is 'yes' every time, unless both Condition 1 and Condition 2 are false. If either one is true, our answer is 'yes'; that is, the whole statement is true. OR functions result in more qualifying responses.

Logic Illustrated

Let's say we're giving free shipping on some of our orders. In the first scenario, shipping is free only if the order is over one hundred fins AND the ship to address is inside Florin, our home country. In this case, we've restricted our results by demanding that both criteria be met.

Possible pseudo–code might look like this:

if ((TotalCost > 100 fins) AND (ShipToCountry = 'Florin')) then ShipCost = 0

Next month, we're feeling generous (or perhaps sales didn't jump as much as we hoped when we introduced free shipping.) Anyway, we've decided to give free shipping if the order totals over one hundred fins OR the ship to address is in Florin. By allowing either criterion to be met, we've relaxed our results to include a broader range of potential recipients.

Possible pseudo–code might look like this:

if ((TotalCost > 100 fins) OR (ShipToCountry = 'Florin')) then ShipCost = 0

Armed with this knowledge, we can see that 'Any of these words' is just an OR function, and 'All of these words' is an AND function. 'This exact phrase' as Boolean logic is slightly more complex than we have room to go into in this article.

Potential Illogical Results

That's all fine if we want to verify that our input matches the two criteria. But what if we want to ensure that it doesn't match them? In a slightly modified scenario, let's imagine we're NOT offering free shipping at home in Florin, and we're not offering it to our neighboring country of Guilder, either. Everybody else, however, gets free shipping. So, if the ship to address isn't in Florin or Guilder, they win.

Boolean logic, as it's applied in electronic circuitry, has nifty functions called NAND and NOR (among others.) I won't go into much detail except to state that the 'N' at the beginning means 'NOT.' These 'truth tables' (the diagrams we used above) are created by taking the AND and OR tables above and simply reversing all the output values. Sounds like a simple solution, right? If we want to make sure we're not matching this OR that, just use something like this bit of pseudo–code:

if (NOT(ShipToCountry = 'Florin') OR NOT(ShipToCountry = 'Guilder')) then ShipCost = 0

We just gave away a lot of free shipping. Here's why: hand me an order; any order. Is the shipping address NOT in Florin? No, it is in Florin? It fails this criterion; no free shipping. But wait; let's analyze the second criterion. Is the shipping address NOT in Guilder? Sure is; NOT in Guilder, I mean. So, since an OR statement only requires one of the criteria to resolve to TRUE, this order gets free shipping.

And, because every single location on earth is either NOT Florin or NOT Guilder (or maybe, NOT both) every single order gets free shipping.

Here's what we want: negate each condition, and connect them with an AND statement:

if (NOT(ShipToCountry = 'Florin') AND NOT(ShipToCountry = 'Guilder')) then ShipCost = 0

or, to more closely match the NOR table by creating an OR condition, then negating the whole thing:

if NOT((ShipToCountry = 'Florin') OR (ShipToCountry = 'Guilder')) then ShipCost = 0

You'll probably find it easier to keep track, though, if you aggregate your criteria with ANDs rather than keeping track of the sometimes unexpected results when using ORs.

Complex Nesting

Of course, logic isn't always this simple. It's possible to string together more than one AND with more than one OR and then throw in some NOTs just for good measure. For instance, now those nuts in marketing are offering free shipping to anyone NOT in Florin or Guilder, unless they spend more than 100 fins.

Let's take our 'not in either country' bit, and add an OR to it:

if (NOT(ShipToCountry = 'Florin') AND NOT(ShipToCountry = 'Guilder') OR (TotalCost > 100 fins)) then ShipCost = 0

Testing Your Logic

If you've written some logic using ANDs, ORs, or both, and the results aren't what you expected, try simplifying. If you're testing multiple criteria simultaneously, try separating them into discrete steps, and outputting the results of each step to the screen. Follow the path, and see where you're getting a TRUE when you expected FALSE, or whatever.

Sometimes it helps to simplify the conditions, not just the logic. That's what I did to test the logic in the pseudo–code for this article. Set a few variables equal to 1 for TRUE or 0 for FALSE, and write your logic using simple equations. For instance, if we make x equal 'shipping to Florin', y equal 'shipping to Guilder', and z equal 'total is over 100 fins', we could write the bit above thus:

if (NOT(x = 1) AND NOT(y = 1) OR (z = 1) then RESULT = TRUE

To test each combination, set x = 1 for an order shipping to Florin, or 0 for an order shipping elsewhere. Follow the same logic for y (Guilder) and z (over or under 100 fins), and you can test all six possibilities pretty quickly, verifying that your logic is, well, logical.

Yes, in this scenario, there are only six possible cases. How do we know that? I'm not telling. We'll cover permutations and factorials some other time.

My consulting service The Commonsense Entrepreneur mentors service related small businesses in customer-centric thinking as a primary tool to reach your goals. I am also a co-founder of the Northern California Association of Entrepreneurs, a support community promoting self-education and cross-pollenation of ideas for entrepreneurs. My book "49 Commonsense Business Observations" was published the first quarter of 2008. My second book "The Commonsense Entrepreneur" will be published during the second quarter of 2008.

Missing )

Submitted by NZJoe on December 16, 2002 - 13:12.

Complex Nesting... if (NOT(ShipToCountry = 'Florin') AND NOT(ShipToCountry = 'Guilder') OR (TotalCost > 100 fins) then ShipCost = 0

login or register to post comments

Nice article, but...

Submitted by dusoft on December 17, 2002 - 10:04.

everyone working with computers should know this. Kids learn this during their first year at high school. It is quite uneasy to understand everything, but still the basic logic:
  • 1 AND 1 => 1
  • 1 AND 0 => 0
  • 1 OR 1 => 1
  • 0 OR 1 => 0
  • is easy to understand even for children 14 or 15 years old. But as I said: "nice article" and sometimes it is important to point out some facts to remember them better :-)

    login or register to post comments

    Mistake made ;-O

    Submitted by dusoft on December 17, 2002 - 10:06.

    Of course, last line should be as following (copy&paste you know...):
  • 0 OR 1 => 1

  • login or register to post comments

    What about XOR?

    Submitted by shotgun on December 19, 2002 - 07:36.

    There is another logic function that was not mentioned here and can also be invaluable in some scenarios. The XOR function (eXclusive OR), its logic table is as follows.

    0 XOR 0 => 0
    1 XOR 0 => 1
    0 XOR 1 => 1
    1 XOR 1 => 0

    It is only TRUE if the entries are different. It can be used, for example on a form validation script to check that someone has clicked either check or credit card, but not both or left both blank. One or the other must have been selected.

    Also, the article does not delve into the really DEEP waters of complex logic, where more than 2 conditions must be tested. Has anyone had to verify 4 or 5 conditions in a single statement? I have.

    Otherwise, a very good article on the basics of logic conditions

    login or register to post comments

    reply: What about XOR?

    Submitted by spinhead on December 19, 2002 - 09:38.

    shotgun:

    Yes, it's intended to be a basic article for beginners, not a thorough treatise on the subject.

    Perhaps you could help us out by writing a more advanced article, and include the info on those more complex statements you mention.

    login or register to post comments

    Sorry...

    Submitted by shotgun on December 19, 2002 - 15:06.

    No offense was intented by my commentary. I just thought that XOR function must be mentioned (it is in Basic Logic classes, at least in electronics). I understand the article is just the basics, and I will look into writing a more advanced one for the "hard-cores". Right now, I'm looking into Regex expressions and how to make them more easily understood by most programmers that feel stumped when they encounter them for the first time. I just read your article on "How to write a how-to" and I will definitely use it for writing my articles. Keep tuned!

    login or register to post comments

    No offense taken; get those articles written!

    Submitted by spinhead on December 19, 2002 - 15:16.

    It was the second comment about the 'basic-ness' of the article, so I wanted to be sure that point was clear.

    Looking forward to your articles—I really need to brush up on regexps and higher logic.

    Thanks for the feedback.

    login or register to post comments

    Boolean generator

    Submitted by ppk on December 26, 2002 - 06:04.

    Years ago I wrote a Boolean generator script that helps you to understand Boolean logic by allowing you to evaluate your own Boolean statements.

    If you find this article interesting but still aren't sure how Boolean logic actually works, you might try it.

    login or register to post comments

    Regexp

    Submitted by sephiroth on December 2, 2003 - 13:33.

    Just to mention it, shotgun: I learned regexp from www.regular-expressions.info, took a good 2 hours of reading for me to be able to write an e-mail validation pattern from scratch, and after that it's just practice to get better at more complex patterns ... you might find it easier to simply post a link to that site, or any of the other 29,200 results I got when googling for "regexp tutorial" :) However, I too would be interested in a tutorial on more advanced logic; perhaps you could even write a little intro to formal logic, with the [upside-down A] and [backward E] and the other symbols used therein. Good luck!

    spinhead: Great article. A little on the basic side, but clearly that was intentional ... I still think that even as an introduction for total beginners, you might've included some of the more traditional "CompSci" versions of these things (think Monte Carlo), as were partially included by some people in the comments. Also, the Florin and Guilder text, while a useful example, was a little bit garbled. Still, I liked it.

    login or register to post comments

    The access keys for this page are: ALT (Control on a Mac) plus:

    evolt.orgEvolt.org is an all-volunteer resource for web developers made up of a discussion list, a browser archive, and member-submitted articles. This article is the property of its author, please do not redistribute or use elsewhere without checking with the author.