Just the Facts Ma’m

What does a PHP geek do when confronted with the task of generating practice math problems for his eight year old daughter? Script it, of course. Madeline wanted to practice addition, so she gave me a crayon and told me to write down 100 math problems consisting of adding two single digit numbers.

A “better” solution lept to mind immediatly:

A class to store and render a “fact”:

<?php

class Fact {
    protected $top;
    protected $bottom;
    
    public function __construct($t, $b) {
        $this->top = $t;
        $this->bottom = $b;
    }
    
    public function render() {
        return '&nbsp;'.$this->top."\n<u>+".$this->bottom.'</u>&nbsp;';
    }
}

?>

Generate some facts and store them in an array:

<?php

$facts = array();

foreach(range(0,9) as $top) {
    foreach(range(0,9) as $bottom) {
        $facts[] = new Fact($top, $bottom);
    }
}

?>

Make sure they are in random order:

<?php

shuffle($facts);

?>

and render them into a table for easy layout (what can I say, it was a two minute hack):

<?php

echo '<table border="0" cellpadding="9">';

foreach(range(0,9) as $tens) {
    echo '<tr>';
        foreach(range(0,9) as $ones) {
            echo '<td>', $facts[$tens*10+$ones]->render(), '</td>';
        }
    echo '</tr>';
}
echo '</tr></table>';

?>

fresh, randomly ordered fact sheet ready for printing.