40% off everything — use code SAVE40 at checkout · ends in …
Skip to content
phpguru.store

Basic PHP Programs with Examples and Output

By Prakash Panthi, Founder · Published September 27, 2026

These basic PHP programs are the classic exercises every beginner writes — even or odd, factorial, Fibonacci, prime numbers, palindromes, tables, calculators and more. Each one is short, uses modern PHP 8, and is shown with its real output (every program on this page was run to produce the output you see). Copy one into a file such as test.php, run it with php test.php or in XAMPP at http://localhost/, then change it and run it again — that's how PHP sticks.

The programs

  1. Hello World
  2. Variables and data types
  3. Even or odd number
  4. Largest of three numbers
  5. Sum of numbers from 1 to N
  6. Multiplication table
  7. Factorial of a number
  8. Fibonacci series
  9. Prime number check
  10. Reverse a string
  11. Palindrome check
  12. Sum of digits
  13. Leap year check
  14. Simple interest calculator
  15. Celsius to Fahrenheit
  16. Array sum, average, largest and smallest
  17. Sort an array
  18. Count vowels in a string
  19. Simple calculator with match
  20. Grade from marks
  21. Current date and time
  22. Reading a form safely

1. Hello World

The first program everyone writes: print text to the page.

<?php
echo "Hello, World!";

Output:

Hello, World!

2. Variables and data types

Store a string, an integer, a float and a boolean, and print them.

<?php
$name = "Asha";
$age = 21;
$height = 1.62;
$isStudent = true;

echo "Name: $name\n";
echo "Age: $age\n";
echo "Height: $height m\n";
echo "Student: " . ($isStudent ? "yes" : "no") . "\n";

Output:

Name: Asha
Age: 21
Height: 1.62 m
Student: yes

3. Even or odd number

Use the modulus operator % to check whether a number divides by 2.

<?php
$number = 17;

if ($number % 2 === 0) {
    echo "$number is even";
} else {
    echo "$number is odd";
}

Output:

17 is odd

4. Largest of three numbers

Compare three values with if / elseif — then the one-line version with max().

<?php
$a = 12;
$b = 45;
$c = 30;

if ($a >= $b && $a >= $c) {
    $largest = $a;
} elseif ($b >= $c) {
    $largest = $b;
} else {
    $largest = $c;
}
echo "Largest: $largest\n";
echo "Using max(): " . max($a, $b, $c);

Output:

Largest: 45
Using max(): 45

5. Sum of numbers from 1 to N

A for loop that adds every number up to N.

<?php
$n = 100;
$sum = 0;
for ($i = 1; $i <= $n; $i++) {
    $sum += $i;
}
echo "Sum of 1 to $n = $sum";

Output:

Sum of 1 to 100 = 5050

6. Multiplication table

Print the table of any number with a loop.

<?php
$number = 7;
for ($i = 1; $i <= 10; $i++) {
    echo "$number x $i = " . ($number * $i) . "\n";
}

Output:

7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
7 x 6 = 42
7 x 7 = 49
7 x 8 = 56
7 x 9 = 63
7 x 10 = 70

7. Factorial of a number

Multiply 1 × 2 × … × n. Shown with a loop and with a recursive function.

<?php
function factorial(int $n): int
{
    return $n <= 1 ? 1 : $n * factorial($n - 1);
}

$result = 1;
for ($i = 1; $i <= 5; $i++) {
    $result *= $i;
}
echo "5! with a loop = $result\n";
echo "6! with recursion = " . factorial(6);

Output:

5! with a loop = 120
6! with recursion = 720

8. Fibonacci series

Each number is the sum of the two before it.

<?php
$count = 10;
$a = 0;
$b = 1;
$series = [];
for ($i = 0; $i < $count; $i++) {
    $series[] = $a;
    [$a, $b] = [$b, $a + $b];
}
echo implode(", ", $series);

Output:

0, 1, 1, 2, 3, 5, 8, 13, 21, 34

9. Prime number check

A number is prime if nothing from 2 up to its square root divides it.

<?php
function isPrime(int $n): bool
{
    if ($n < 2) {
        return false;
    }
    for ($i = 2; $i * $i <= $n; $i++) {
        if ($n % $i === 0) {
            return false;
        }
    }
    return true;
}

foreach ([2, 15, 29, 97, 100] as $n) {
    echo $n . (isPrime($n) ? " is prime" : " is not prime") . "\n";
}

Output:

2 is prime
15 is not prime
29 is prime
97 is prime
100 is not prime

10. Reverse a string

The built-in strrev(), and a loop that does the same thing.

<?php
$text = "phpguru";
echo strrev($text) . "\n";

$reversed = "";
for ($i = strlen($text) - 1; $i >= 0; $i--) {
    $reversed .= $text[$i];
}
echo $reversed;

Output:

urugphp
urugphp

11. Palindrome check

A word that reads the same backwards, ignoring case and spaces.

<?php
function isPalindrome(string $text): bool
{
    $clean = strtolower(preg_replace("/[^a-z0-9]/i", "", $text));
    return $clean === strrev($clean);
}

foreach (["Madam", "Never odd or even", "phpguru"] as $word) {
    echo "\"$word\" " . (isPalindrome($word) ? "is" : "is not") . " a palindrome\n";
}

Output:

"Madam" is a palindrome
"Never odd or even" is a palindrome
"phpguru" is not a palindrome

12. Sum of digits

Add the digits of a number using % 10 and integer division.

<?php
$number = 45829;
$sum = 0;
$n = $number;
while ($n > 0) {
    $sum += $n % 10;
    $n = intdiv($n, 10);
}
echo "Sum of digits of $number = $sum";

Output:

Sum of digits of 45829 = 28

13. Leap year check

Divisible by 4, except centuries, unless divisible by 400.

<?php
function isLeapYear(int $year): bool
{
    return ($year % 4 === 0 && $year % 100 !== 0) || $year % 400 === 0;
}

foreach ([1900, 2000, 2024, 2026] as $year) {
    echo $year . (isLeapYear($year) ? " is a leap year" : " is not a leap year") . "\n";
}

Output:

1900 is not a leap year
2000 is a leap year
2024 is a leap year
2026 is not a leap year

14. Simple interest calculator

Simple interest = principal × rate × time ÷ 100.

<?php
$principal = 50000;
$rate = 7.5;
$years = 3;

$interest = $principal * $rate * $years / 100;
$total = $principal + $interest;

echo "Interest: " . number_format($interest, 2) . "\n";
echo "Total amount: " . number_format($total, 2);

Output:

Interest: 11,250.00
Total amount: 61,250.00

15. Celsius to Fahrenheit

Temperature conversion with a function and rounding.

<?php
function toFahrenheit(float $celsius): float
{
    return round($celsius * 9 / 5 + 32, 1);
}

foreach ([0, 25, 37, 100] as $c) {
    echo "$c °C = " . toFahrenheit($c) . " °F\n";
}

Output:

0 °C = 32 °F
25 °C = 77 °F
37 °C = 98.6 °F
100 °C = 212 °F

16. Array sum, average, largest and smallest

Built-in array functions do the work.

<?php
$marks = [72, 95, 88, 61, 90];

echo "Total: " . array_sum($marks) . "\n";
echo "Average: " . round(array_sum($marks) / count($marks), 2) . "\n";
echo "Highest: " . max($marks) . "\n";
echo "Lowest: " . min($marks);

Output:

Total: 406
Average: 81.2
Highest: 95
Lowest: 61

17. Sort an array

Sort numbers ascending and descending, and an associative array by value.

<?php
$numbers = [42, 7, 19, 88, 3];
sort($numbers);
echo "Ascending: " . implode(", ", $numbers) . "\n";
rsort($numbers);
echo "Descending: " . implode(", ", $numbers) . "\n";

$scores = ["Asha" => 91, "Ravi" => 78, "Meera" => 85];
arsort($scores);
foreach ($scores as $name => $score) {
    echo "$name: $score\n";
}

Output:

Ascending: 3, 7, 19, 42, 88
Descending: 88, 42, 19, 7, 3
Asha: 91
Meera: 85
Ravi: 78

18. Count vowels in a string

Loop over each character and count a, e, i, o, u.

<?php
$text = "Learning PHP is fun";
$count = 0;
foreach (str_split(strtolower($text)) as $char) {
    if (in_array($char, ["a", "e", "i", "o", "u"], true)) {
        $count++;
    }
}
echo "Vowels in \"$text\": $count";

Output:

Vowels in "Learning PHP is fun": 5

19. Simple calculator with match

PHP 8 match expression picks the operation.

<?php
function calculate(float $a, float $b, string $op): string
{
    return match ($op) {
        "+" => (string) ($a + $b),
        "-" => (string) ($a - $b),
        "*" => (string) ($a * $b),
        "/" => $b == 0 ? "Cannot divide by zero" : (string) ($a / $b),
        default => "Unknown operator",
    };
}

echo "12 + 5 = " . calculate(12, 5, "+") . "\n";
echo "12 / 4 = " . calculate(12, 4, "/") . "\n";
echo "12 / 0 = " . calculate(12, 0, "/");

Output:

12 + 5 = 17
12 / 4 = 3
12 / 0 = Cannot divide by zero

20. Grade from marks

Turn a percentage into a grade with if / elseif.

<?php
function grade(int $marks): string
{
    if ($marks >= 90) return "A";
    if ($marks >= 75) return "B";
    if ($marks >= 50) return "C";
    return "F";
}

foreach (["Asha" => 93, "Ravi" => 67, "Meera" => 45] as $name => $marks) {
    echo "$name: $marks% = grade " . grade($marks) . "\n";
}

Output:

Asha: 93% = grade A
Ravi: 67% = grade C
Meera: 45% = grade F

21. Current date and time

Format dates with date() and set the timezone.

<?php
date_default_timezone_set("Asia/Kolkata");
$now = new DateTime("2026-09-28 14:30:00");

echo $now->format("l, j F Y") . "\n";
echo $now->format("d/m/Y H:i") . "\n";
$nextWeek = (clone $now)->modify("+7 days");
echo "One week later: " . $nextWeek->format("j M Y");

Output:

Monday, 28 September 2026
28/09/2026 14:30
One week later: 5 Oct 2026

22. Reading a form safely

Read a submitted value, validate it and escape it before printing. (Run this one in a browser: open form.php?name=Asha.)

<?php
$name = trim($_GET["name"] ?? "");

if ($name === "") {
    echo "Please enter your name.";
} elseif (mb_strlen($name) > 50) {
    echo "That name is too long.";
} else {
    echo "Hello, " . htmlspecialchars($name, ENT_QUOTES, "UTF-8") . "!";
}

Output:

Please enter your name.

Good habits these programs show

  • Use === for comparisons — it checks type as well as value.
  • Put repeated logic in functions with type declarations (int $n, : bool) — PHP then catches wrong inputs for you.
  • Escape anything a user typed with htmlspecialchars() before printing it — program 22 shows why.
  • Use built-in functions such as max(), array_sum() and strrev() — then write your own version once to understand them.

Next steps

Once these feel easy, the next step is programs that use forms and a database. PHP Foundations teaches PHP basics step by step — forms, sessions, MySQL with PDO and security — ending with a real app; lesson 1 is free. For project ideas, see 20 PHP project ideas, and for complete working applications, the PHP projects with source code catalog.