Skip to content

Instantly share code, notes, and snippets.

@alastairparagas
Created March 2, 2015 03:20
Show Gist options
  • Save alastairparagas/c0a350b7747da91ec958 to your computer and use it in GitHub Desktop.
Save alastairparagas/c0a350b7747da91ec958 to your computer and use it in GitHub Desktop.
Crackle Pop - Factorization
<?php
// In PHP, variables are function-scoped. Use call_user_func to prevent global pollution.
call_user_func(
function() {
for ($i=1; $i<101; $i++) {
// Reset variables every loop as PHP variables are function scoped, not block scoped.
$divisibleBy3 = false;
$divisibleBy5 = false;
// By default, print number
$toPrint = $i;
// If divisible by 3, print "Crackle" instead
if ($i % 3 == 0) {
$toPrint = "Crackle";
$divisibleBy3 = true;
}
// If divisible by 5, print "Pop" instead
if ($i % 5 == 0) {
$toPrint = "Pop";
$divisibleBy5 = true;
}
// If divisible by 3 and 5, print "CracklePop" instead
if ($divisibleBy3 && $divisibleBy5) {
$toPrint = "CracklePop";
}
// Print out variable
echo $toPrint . "<br>";
}
}
);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment