Learn HACK with Real Code Examples
Updated Nov 20, 2025
Code Sample Descriptions
1
Hack Counter and Theme Toggle
<?hh
<<__EntryPoint>>
function main(): void {
$counter = 0;
$isDark = false;
function updateUI(): void {
global $counter, $isDark;
echo "Counter: $counter\n";
echo "Theme: " . ($isDark ? "Dark" : "Light") . "\n";
}
function increment(): void {
global $counter;
$counter += 1;
updateUI();
}
function decrement(): void {
global $counter;
$counter -= 1;
updateUI();
}
function reset(): void {
global $counter;
$counter = 0;
updateUI();
}
function toggleTheme(): void {
global $isDark;
$isDark = !$isDark;
updateUI();
}
// Simulate actions
updateUI();
increment();
increment();
toggleTheme();
decrement();
reset();
}
Demonstrates a simple counter with theme toggling using Hack variables, functions, and conditional statements.
2
Hack Fibonacci Sequence
<?hh
function fib(int $n): int {
return $n < 2 ? $n : fib($n-1) + fib($n-2);
}
<<__EntryPoint>>
function main(): void {
for ($i = 0; $i < 10; $i++) {
echo fib($i) . "\n";
}
}
Generates first 10 Fibonacci numbers using recursion.
3
Hack Factorial Calculator
<?hh
function factorial(int $n): int {
return $n === 0 ? 1 : $n * factorial($n - 1);
}
<<__EntryPoint>>
function main(): void {
echo factorial(5) . "\n";
}
Calculates factorial of a number using recursion.
4
Hack Prime Checker
<?hh
function isPrime(int $n): bool {
if ($n < 2) return false;
for ($i = 2; $i < $n; $i++) {
if ($n % $i === 0) return false;
}
return true;
}
<<__EntryPoint>>
function main(): void {
echo isPrime(13) ? "Prime\n" : "Not Prime\n";
}
Checks if a number is prime.
5
Hack Sum of Array
<?hh
<<__EntryPoint>>
function main(): void {
$nums = vec[1,2,3,4,5];
$sum = array_sum($nums);
echo $sum . "\n";
}
Calculates sum of an array of numbers.
6
Hack Reverse String
<?hh
<<__EntryPoint>>
function main(): void {
$s = "HELLO";
echo strrev($s) . "\n";
}
Reverses a string.
7
Hack Multiplication Table
<?hh
<<__EntryPoint>>
function main(): void {
$n = 5;
for ($i = 1; $i <= 10; $i++) {
echo "$n x $i = " . ($n * $i) . "\n";
}
}
Prints multiplication table of a number.
8
Hack Celsius to Fahrenheit
<?hh
<<__EntryPoint>>
function main(): void {
$c = 25;
$f = ($c * 9 / 5) + 32;
echo $f . "\n";
}
Converts Celsius to Fahrenheit.
9
Hack Simple Alarm Simulation
<?hh
<<__EntryPoint>>
function main(): void {
$temp = 80;
$thresh = 75;
echo ($temp > $thresh ? "Alarm: Temperature Too High!\n" : "Temperature Normal\n");
}
Simulates an alarm if a threshold is exceeded.
10
Hack Random Walk Simulation
<?hh
<<__EntryPoint>>
function main(): void {
$steps = 10;
$pos = 0;
for ($i = 0; $i < $steps; $i++) {
$pos += (rand(0,1) === 0 ? -1 : 1);
echo $pos . "\n";
}
}
Simulates a 1D random walk.