Skip to content
Tutorials Center
My learning

Topics

Lesson 140 of 147 · Practice and Review

PHP Programs: 50 Classic Examples

50 classic PHP programs with output: primes, factorial, Fibonacci, palindromes, Roman numerals, word counts, sorting, matrices, dates, CSV, JSON and classes.

Every PHP developer has written the same small classics at some point: check whether a number is prime, reverse a string, count the words in a text, group a list of records by one field, turn a CSV file into JSON. They are short enough to read in a minute, yet each one trains a real skill: loops with the right bounds, choosing the right built-in function, handling multibyte text, working with arrays as ordered maps. This page collects 50 of them, all written from scratch in clean, modern PHP 8.5.

Every program is complete and runs as it is. Press Run and our server executes it with the PHP 8.5 command-line interpreter and shows the output underneath. Change the numbers, break something on purpose, and run again. Programs that read input come with values already in the Input box, so you can edit those too. Each example has a short explanation and a link to the lesson that covers the idea in depth.

A few habits run through the whole page. Programs with several functions start with declare(strict_types=1);, so a wrong argument type is an error instead of a silent conversion. Functions have type declarations for parameters and return values. Text that could contain non-English letters goes through the mb_* functions. And where PHP has a built-in function that solves the problem, the program shows it next to the hand-written version, because in real code you should use the built-in. If you would rather write these yourself before reading ours, try the practice exercises first.

Basics and input

These practice output, variables, arithmetic and if statements. Reading input works with fgets(STDIN), which returns one line (or false when there is no more input), as explained in Command-Line PHP.

1. Sum and average of numbers

Reads every number from the Input box, ignores anything that isn't numeric, and prints the count, the sum and the average. preg_split with \s+ splits on any run of spaces and line breaks, and is_numeric filters out words.

PHP 1. Sum and average

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

2. Even or odd

A number is even when $n % 2 === 0. Compare with 0, not with 1: in PHP the remainder keeps the sign of the left operand, so -7 % 2 is -1, and a test like $n % 2 === 1 would call -7 even.

PHP 2. Even or odd

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

3. Largest of three numbers

The if version keeps a running "largest so far", which is the same idea you use for a whole array. In real code, PHP's max() does it in one call and accepts any number of arguments or a single array. See Math Functions.

PHP 3. Largest of three

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

4. Swap two variables

The classic way uses a temporary variable. Modern PHP swaps in one line with array destructuring: the right side builds an array, the left side unpacks it. A function can only swap the caller's variables when its parameters are passed by reference with &.

PHP 4. Swap two variables

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

5. Simple calculator

Each input line holds an expression such as 12 * 4. A regular expression checks the shape and captures the parts, and a match expression picks the operation. Dividing by zero throws a DivisionByZeroError in PHP 8, so the program checks first and prints a friendly message instead.

PHP 5. Simple calculator

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The function's return type float|string is a union type. The match has no default arm because the regular expression only lets the six operators through; any other value would throw an UnhandledMatchError.

6. Leap year

A year is a leap year when it is divisible by 4, except century years, which must also be divisible by 400. So 2024 and 2000 are leap years, but 1900 is not. PHP can confirm the answer: checkdate(2, 29, $year) is true only when February 29 exists that year.

PHP 6. Leap year

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

7. Temperature conversion table

A for loop with a step of 20 and printf field widths produce a tidy table. %6.1f means "at least 6 characters wide, 1 digit after the decimal point". See Formatting Strings.

PHP 7. Temperature table

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Loops and number theory

These practice loops, functions, recursion and the integer and float rules.

8. Factorial

n! grows very fast. A 64-bit PHP integer holds up to PHP_INT_MAX (about 9.2 × 10¹⁸), which is enough for 20!. One step later the multiplication overflows, and PHP quietly switches to a float, losing exact digits. For exact big results, use the gmp or bcmath extensions, which work with numbers of any size.

PHP 8. Factorial

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

var_dump shows the type change: int(2432902008176640000) for 20!, then float(5.109094217170944E+19) for 21!. Both big-number versions print the exact 26-digit value of 25!.

9. Fibonacci sequence

Each Fibonacci number is the sum of the two before it. A generator produces the sequence lazily, one value at a time, so the caller decides how many it needs. The naive recursive version recalculates the same values over and over; the generator does each step once.

PHP 9. Fibonacci

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

10. Prime check

A number n is prime when it is greater than 1 and has no divisor other than 1 and itself. You only need to try divisors up to the square root of n: if n = a × b and both were larger than √n, their product would be larger than n. Checking 2 separately lets the loop skip every other even number.

PHP 10. Prime check

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

11. All primes up to N (Sieve of Eratosthenes)

To list many primes, crossing out multiples is much faster than testing each number. array_fill creates the table of flags, and each prime p starts crossing out at p * p, because smaller multiples of p were already crossed out by a smaller prime factor. array_keys($isPrime, true) collects the indexes that are still true. See Array Functions.

PHP 11. Sieve of Eratosthenes

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

12. GCD and LCM

Euclid's algorithm replaces the pair (a, b) with (b, a % b) until b is zero; what remains is the greatest common divisor. The least common multiple follows from lcm(a, b) = a / gcd(a, b) * b (dividing first keeps the intermediate value small). The gmp extension has both built in.

PHP 12. GCD and LCM

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

13. Reverse a number and sum its digits

% 10 gives the last digit and intdiv($n, 10) removes it. The same loop can build the reversed number and add up the digits. PHP also offers a string shortcut: strrev((string) $n) and array_sum(str_split((string) $n)), which is fine for display but returns strings and doesn't handle the minus sign.

PHP 13. Reverse and digit sum

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Note that 1200 reverses to 21: leading zeros disappear in a number.

14. Palindrome number

A number is a palindrome when it reads the same backward, like 12321. The arithmetic version reverses the digits and compares; the string version compares the text with strrev of itself. Negative numbers are not palindromes, because -121 reversed would be 121-.

PHP 14. Palindrome number

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

15. Armstrong numbers

An Armstrong number equals the sum of its digits, each raised to the power of the number of digits: 153 = 1³ + 5³ + 3³. Here the string form is the easiest way to get the digits, and array_map turns them into powers. See array_map, array_filter and array_reduce.

PHP 15. Armstrong numbers

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

isArmstrong(...) is the first-class callable syntax (PHP 8.1): it turns the function into a closure you can pass to array_filter. The output lists 1 to 9 (every one-digit number qualifies), then 153, 370, 371, 407, 1634, 8208, 9474, 54748, 92727 and 93084.

16. Perfect numbers

A perfect number equals the sum of its proper divisors: 28 = 1 + 2 + 4 + 7 + 14. Divisors come in pairs (d and n / d), so the loop again stops at the square root and adds both members of each pair.

PHP 16. Perfect numbers

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

17. FizzBuzz with match(true)

The famous screening question: print the numbers 1 to 15, but Fizz for multiples of 3, Buzz for multiples of 5 and FizzBuzz for both. match (true) tries each condition in order and returns the first arm whose condition is true, so the "both" case must come first.

PHP 17. FizzBuzz

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

18. Multiplication table

Two nested loops build a 10 × 10 grid. str_pad with STR_PAD_LEFT right-aligns each value in a 4-character column, which is the same thing printf('%4d') does. See String Functions.

PHP 18. Multiplication table

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

19. Prime factorization

Divide by 2 while you can, then by 3, 5, 7 and so on. Each divisor that works is automatically prime, because its own smaller factors were already divided out. Whatever is left above 1 at the end is the last prime factor. array_count_values turns the list into exponents.

PHP 19. Prime factorization

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Number bases and formatting

These practice math functions, string formatting and associative arrays.

20. Decimal to binary, octal and hexadecimal

PHP has a function for every common base: decbin, decoct, dechex and back with bindec, octdec, hexdec. base_convert handles any base from 2 to 36. The hand-written version shows the algorithm behind them: repeatedly take the remainder by the base, then reverse the digits.

PHP 20. Base conversion

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

21. Roman numerals

Converting to Roman numerals is a greedy algorithm: walk through the values from largest to smallest, including the subtractive pairs like CM (900) and IV (4), and take each one as often as it fits. An associative array keeps the symbols and values together in the right order. Converting back adds each symbol's value, but subtracts it when a larger symbol follows.

PHP 21. Roman numerals

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

22. Number to words

Writing a number in English words splits it into groups of three digits (ones, thousands, millions, billions) and names each group. A small recursive helper handles anything below 1000. See Recursion.

PHP 22. Number to words

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

23. Human-readable file sizes

Byte counts like 1536000 are hard to read. Divide by 1024 until the value is below 1024, counting how many times you divided to pick the unit. number_format then rounds the result and adds thousands separators.

PHP 23. Human-readable file sizes

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The last line uses a named argument, which makes the meaning of the 3 obvious at the call site.

Strings

These practice string functions, multibyte strings and regular expressions.

24. Reverse a string

strrev reverses bytes, which is fine for plain ASCII text but breaks UTF-8 letters that take several bytes, such as é or ü. For any human text, split it into characters with mb_str_split, reverse the array, and join it again.

PHP 24. Reverse a string

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The last line shows why strrev fails: é is the two bytes c3 a9, and reversing them gives a9 c3, which isn't valid UTF-8.

25. Palindrome sentence

A sentence like "Was it a car or a cat I saw?" is a palindrome once you ignore case, spaces and punctuation. preg_replace with \P{L} (anything that is not a letter) and the u flag removes everything but letters in any alphabet, and mb_strtolower lowercases them.

PHP 25. Palindrome sentence

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The French sentence is reported as "not a palindrome" only because é and e are different characters; removing accents first, as program 31 does, would make it pass. Also notice that its result sits one column too far left: printf pads by bytes, and É takes two. mb_str_pad (PHP 8.3) pads by characters when alignment matters.

26. Count vowels, consonants, digits and spaces

preg_match_all returns how many matches it found, so one call per category counts the whole string. The character classes [aeiou] and [b-df-hj-np-tv-z] with the i flag cover upper and lower case.

PHP 26. Count character types

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

27. Word frequency

A classic text-processing pipeline: lowercase the text, extract the words with a regular expression, count them with array_count_values, and sort by count with arsort, which keeps the word keys. array_slice with preserve_keys takes the top five. See Sorting Arrays.

PHP 27. Word frequency

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Since PHP 8.0 sorting is stable, so words with the same count keep the order in which they first appeared.

28. Anagram check

Two words are anagrams when they use the same letters the same number of times, like "listen" and "silent". Normalize both strings (lowercase, letters only), then compare their letter counts. count_chars($text, 1) returns an array of byte value => count; for multibyte text, array_count_values(mb_str_split(...)) does the same per character.

PHP 28. Anagram check

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

=== on two arrays is true only when they have the same key/value pairs in the same order, which is why both arrays are sorted by key first.

29. Case conversions: title case, camelCase, snake_case

Code generators and frameworks constantly convert between naming styles. ucwords capitalizes each word, and regular expressions handle the rest: preg_split breaks any style into words, and two small functions assemble the target style.

PHP 29. Case conversions

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The lookbehind/lookahead pattern inserts a space wherever a lowercase letter or digit is followed by an uppercase letter. Notice that parseJSONResponse becomes parse_jsonresponse: an acronym directly followed by a capitalized word is ambiguous, which is why many style guides write parseJsonResponse.

30. Run-length encoding

Run-length encoding replaces runs of the same character with a count: aaabcc becomes 3a1b2c. A backreference in a regular expression finds runs, and preg_replace_callback builds the replacement. Decoding reverses the process.

PHP 30. Run-length encoding

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

This simple format can't encode digits in the input, because the decoder could not tell counts from data. Real formats escape them or store counts as bytes.

31. URL slugs

A slug is the readable part of a URL, like /blog/my-first-post. Lowercase the title, turn accented letters into plain ones, drop apostrophes, replace every run of other characters with a single hyphen, and trim hyphens from the ends. strtr with a lookup table does the accent replacement predictably. (iconv('UTF-8', 'ASCII//TRANSLIT', ...) is often suggested, but its output depends on the system's iconv library: on our server it turns è into `e. The intl extension's Transliterator is the complete solution where it's installed.)

PHP 31. URL slugs

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

32. Validate and extract email addresses

filter_var($value, FILTER_VALIDATE_EMAIL) returns the address when it looks valid and false otherwise. It checks the syntax only; whether the mailbox exists can only be confirmed by sending a message. To find addresses inside longer text, a simple regular expression collects candidates, and the filter confirms each one. See Form Validation.

PHP 32. Validate emails

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

x@localhost is rejected because the filter requires a domain with a dot.

33. Random password generator

Passwords and tokens must come from a cryptographically secure source. random_int is one; rand() and mt_rand() are not. The generator below guarantees at least one character from each group and then shuffles with the secure Random\Randomizer (PHP 8.2), because str_shuffle uses the non-secure generator. Your output differs on every run. See Hashing, Encryption and Random Numbers.

PHP 33. Random password generator

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The character groups leave out look-alikes such as l, I, O, 0 and 1, so people can type a password they read from a screen.

Arrays

These practice arrays, array functions, sorting and multidimensional arrays.

34. Sum, average, minimum and maximum

PHP has built-ins for each statistic: array_sum, min, max and count. The median needs a sorted copy; arrays are copied on assignment, so sorting $sorted leaves $scores untouched.

PHP 34. Array statistics

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

35. Second largest element

The second largest distinct value: with [7, 9, 9, 4] the answer is 7, not 9. One pass with two variables does it in linear time. The short version with array_unique and rsort is easier to read and fine for small arrays.

PHP 35. Second largest

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Returning ?int (null when there is no answer) is clearer than a magic value like -1, and the null coalescing operator ?? prints "none" for it.

36. Remove duplicates

array_unique keeps the first occurrence of each value and its original key, so the result can have gaps like 0, 1, 3. Wrap it in array_values to get a clean list. For large arrays of integers or strings, array_flip twice or the "seen" lookup table is faster, because array_unique compares values as strings by default.

PHP 36. Remove duplicates

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The last loop removes duplicates by a normalized key (the lowercase address) while keeping the first spelling, a pattern you need for emails, usernames and tags.

Linear search checks each element in turn and works on any array. Binary search needs a sorted array, but halves the search range at every step, so a million elements take at most 20 comparisons. PHP's array_search is a linear search; pass true as the third argument for strict comparison, or "1e1" would match 10.

PHP 37. Linear and binary search

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Note the order of the output: PHP evaluates all the arguments of echo before printing, so each "found in N steps" line appears before the line that reports the index.

38. Bubble sort and insertion sort

You will use sort and usort in real code, but these two algorithms are interview favorites. Bubble sort swaps neighbors until no swaps are needed; insertion sort grows a sorted prefix by moving each new element left into place. Arrays are passed by value, so each function sorts its own copy and returns it.

PHP 38. Bubble and insertion sort

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

39. Merge two sorted arrays

Two indexes walk through both arrays at once and always take the smaller front element. That is the merge step of merge sort, and it runs in linear time. array_merge followed by sort gives the same result but sorts everything again.

PHP 39. Merge sorted arrays

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The final line of the function uses the spread operator to append whatever is left of either array.

40. Rotate an array

Rotating left by k moves the first k elements to the end. array_slice cuts the array into two parts and array_merge joins them in swapped order. Taking k modulo the length handles large values, and adding the length first turns a negative k (a right rotation) into the matching left rotation.

PHP 40. Rotate an array

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

41. Group records by a field

Grouping is one of the most common tasks in PHP applications: orders by customer, posts by month, people by city. The key trick is $groups[$key][] = $row;, which creates the inner array the first time a key appears. array_column then pulls one field out of each record.

PHP 41. Group records

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

array_column($people, 'age', 'name') with a third argument builds a lookup table: names as keys, ages as values.

Matrices and patterns

These practice multidimensional arrays, nested loops and string functions.

42. Matrix multiplication and transpose

A matrix is an array of rows. Each cell of the product is the dot product of a row of A and a column of B, so A must have as many columns as B has rows. Transposing has a famous PHP one-liner: array_map(null, ...$matrix) zips the rows together column by column.

PHP 42. Matrix multiplication

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

One caution about the transpose trick: with a single row, array_map(null, $row) returns the row unchanged instead of a column, so production code often transposes with two loops.

43. Pyramid and Floyd's triangle

Pattern programs train loop bounds. In the pyramid, row r has height - r leading spaces and 2r - 1 stars. Floyd's triangle prints consecutive numbers, one more per row.

PHP 43. Pyramid and Floyd's triangle

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

44. Pascal's triangle

Each number in Pascal's triangle is the sum of the two numbers above it. Every row can be computed from the previous one: start and end with 1, and add neighboring pairs in between. str_pad with STR_PAD_BOTH centers each row.

PHP 44. Pascal's triangle

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Dates

These practice dates and times. The examples use fixed dates so the output stays the same; replace them with new DateTimeImmutable() (meaning "now") in real code.

45. Age and time between dates

DateTimeImmutable::diff returns a DateInterval with years, months and days that respect real month lengths and leap years, which simple division by 365 gets wrong. Its days property holds the total number of days.

PHP 45. Age and date differences

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The second line shows a real edge case: someone born on February 29 is still 0 years old on February 28 of a non-leap year.

46. Print a month calendar

format('N') gives the ISO day of the week (1 = Monday to 7 = Sunday) and format('t') the number of days in the month. The calendar prints blank cells until the first day, then breaks the line after every Sunday.

PHP 46. Month calendar

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Files and data formats

These practice reading and writing files, CSV files and JSON. Files you create in the editor exist only while the program runs.

47. Write a file, then count its lines, words and characters

file_put_contents writes a whole file in one call and file() reads it back as an array of lines. The program creates its file in the system temporary folder with tempnam, and deletes it at the end with unlink, which is the habit to keep for temporary files.

PHP 47. Count lines, words and characters

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

48. CSV to JSON

Reading CSV the right way means fgetcsv (it handles quoted fields with commas inside), using the first row as keys with array_combine, and converting numeric columns. The program reads from a php://temp stream, which behaves exactly like a file. json_encode with JSON_PRETTY_PRINT produces readable JSON, and json_decode turns it back into arrays.

PHP 48. CSV to JSON

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Passing escape: '' turns off PHP's old non-standard escape character, which is the recommended setting and avoids a deprecation notice in PHP 8.4 and later. Notice that the balances -20.0 and 0.0 appear as -20 and 0 in the JSON: a float with no fractional part is written like an integer, so decoding gives back an int. Add the JSON_PRESERVE_ZERO_FRACTION flag if the .0 matters to whoever reads the JSON.

Object-oriented programs

These practice classes and objects, interfaces, exceptions and property hooks and asymmetric visibility.

49. A bank account class

The balance is stored in integer cents, because floats can't represent most decimal amounts exactly. public private(set) (PHP 8.4 asymmetric visibility) lets everyone read the balance but only the class change it. Invalid operations throw exceptions instead of returning error codes.

PHP 49. Bank account

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The third attempt writes to the balance from outside the class, and PHP refuses with an Error ("Cannot modify private(set) property"). Catching Error here is only for the demonstration; in real code it signals a bug to fix, not a condition to handle.

50. Shapes with an interface

An interface defines what every shape can do, and each class decides how. The calling code works with Shape and never needs to know which concrete class it has: that is polymorphism. readonly classes (PHP 8.2) make each shape an immutable value, and usort with the spaceship operator <=> sorts them by area.

PHP 50. Shapes with an interface

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

With strict_types, passing the integer 3 to a float parameter is still allowed: int-to-float is the one widening conversion strict mode permits. That's why new Rectangle(3, 2) works, and why its name prints as 3 x 2.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. In program 2, what does -7 % 2 evaluate to in PHP?

    The result of % takes the sign of the left operand, so -7 % 2 is -1. That's why the even test compares with 0 instead of checking for 1.
  2. 2. What does var_dump(factorial(21)) print in program 8, and why?

    PHP integer arithmetic that overflows produces a float instead of wrapping. 21! is about 5.1 x 10^19, larger than PHP_INT_MAX, so it becomes float(5.109094217170944E+19) and loses exact digits. gmp and bcmath give exact results.
  3. 3. Why does program 24 use mb_str_split instead of strrev to reverse "Crème brûlée"?

    In UTF-8, è is two bytes. Reversing bytes swaps them, which produces an invalid sequence. Splitting into characters first keeps each one intact.
  4. 4. In program 36, what keys does array_unique(['php', 'web', 'php', 'sql']) return?

    array_unique keeps the first occurrence of each value with its original key, so the result has a gap. Wrap it in array_values() for a clean list.

Summary

  • Number programs (primes, GCD, digits, factorization) come down to %, intdiv and loops with good bounds such as $d * $d <= $n. Integer overflow turns into a float, so use gmp or bcmath for exact big numbers and integer cents for money.
  • PHP has a built-in for most classics: max, array_sum, decbin, base_convert, array_count_values, array_unique, array_column, checkdate. Know the algorithm, but use the built-in in real code.
  • Text is bytes: use mb_* functions and regular expressions with the u flag for anything a human writes.
  • Arrays are ordered maps: watch the keys (array_unique, arsort and array_slice with preserve_keys keep them), compare strictly with array_search(..., true), and group with $groups[$key][] = $row.
  • Dates go through DateTimeImmutable and diff; CSV goes through fgetcsv with escape: ''; JSON uses JSON_THROW_ON_ERROR.
  • Small classes with typed properties, private(set), readonly, interfaces and exceptions make even tiny programs safer and clearer.

Next: PHP Practice Exercises, where you write programs like these yourself and compare your solutions with ours.