Search code examples
phptruthtable

Outputting a truth table in PHP


I ran across this truth table generator site, and tried to mimic it in PHP (i realize the source code is available, but i know 0 perl).

Now my question is not about evaluating the expression, but how to output the table so that every combination of T and F for the variables is shown

For example, with 3 variables, the table would look like such:

a | b | c 
-----------
T | T | T  
T | T | F 
T | F | T 
T | F | F 
F | T | T 
F | T | F 
F | F | T 
F | F | F 

and with 4 variables..

a | b | c | d
-------------
T | T | T | T
T | T | T | F
T | T | F | T
T | T | F | F
T | F | T | T
T | F | T | F
T | F | F | T
T | F | F | F
F | T | T | T
F | T | T | F
F | T | F | T
F | T | F | F
F | F | T | T
F | F | T | F
F | F | F | T
F | F | F | F

What is the logic/pattern to create it?


Solution

  • How about this recursive function? It returns a 2-dimensional array where each 'row' has $count elements. You can use this to generate your table.

    function getTruthValues($count) {
        if (1 === $count) {
            // true and false for the first variable
            return array(array('T'), array('F'));
        }   
    
        // get 2 copies of the output for 1 less variable
        $trues = $falses = getTruthValues(--$count);
        for ($i = 0, $total = count($trues); $i < $total; $i++) {
            // the true copy gets a T added to each row
            array_unshift($trues[$i], 'T');
            // and the false copy gets an F
            array_unshift($falses[$i], 'F');
        }   
    
        // combine the T and F copies to give this variable's output
        return array_merge($trues, $falses);
    }
    
    function toTable(array $rows) {
        $return = "<table>\n";
        $headers = range('A', chr(64 + count($rows[0])));
        $return .= '<tr><th>' . implode('</th><th>', $headers) . "</th></tr>\n";
    
        foreach ($rows as $row) {
            $return .= '<tr><td>' . implode('</td><td>', $row) . "</td></tr>\n";
        }
    
        return $return . '</table>';
    }
    
    echo toTable(getTruthValues(3));
    

    EDIT: Codepad, with an added function to convert the array to a table.