Skip to content
Tutorials Center
My learning

Topics

Lesson 143 of 147 ยท Practice and Review

PHP Date and Function Programs: 11 Practical Examples

11 PHP programs with output - weekdays between dates, last day of month, add 24 hours, sort dates, format phone numbers, zero-pad, file extensions, usernames and pass by reference.

This page collects small programs in two families that are rarely taught together but often asked together: dates (how many working days between two dates, what is the last day of this month, what is "tomorrow" across a daylight-saving change) and utility functions (format a phone number, get a file extension, pull a username out of an e-mail address, change a variable through a reference). Each is short, complete and tested on the PHP 8.5 runner.

For dates the rule is always the same: use DateTimeImmutable, set the time zone explicitly and let PHP do the calendar arithmetic, as explained in Date and Time. All examples use fixed dates so that the output is the same every time you press Run.

Dates

1. Count the weekdays between two dates

Use a DatePeriod to iterate each day and skip Saturdays and Sundays. format('N') gives 1 (Monday) to 7 (Sunday). The end date of a DatePeriod is exclusive, so add one day to include it.

PHP 1. Weekdays between dates

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. The last day of a month

modify('last day of this month') handles leap years and different month lengths for you. format('t') gives the number of days directly.

PHP 2. Last day of the month

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. Add 24 hours to a date

"Plus 24 hours" and "plus one day" are different things when a clock change happens. Adding PT24H moves exactly 24 hours on the timeline, while +1 day keeps the wall-clock time. Compare them across the European autumn change on 25 October 2026.

PHP 3. 24 hours or 1 day?

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 clocks go back that night, so 24 hours later is 11:00 local time while "one day" later is still 12:00. For deadlines in a user's calendar use days; for timeouts use hours or seconds.

4. Sort an array of dates

Dates in Y-m-d format sort correctly as plain strings, but other formats do not. Convert to DateTimeImmutable and compare with <=>, which DateTime objects support.

PHP 4. Sort dates

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.

Formatting helpers

5. Format a phone number

Strip everything that is not a digit, check the length, then format with sprintf() and substr(). This example handles ten-digit numbers; real systems use a library built on international rules.

PHP 5. Phone number format

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.

6. Add leading zeros

str_pad() pads strings on the left or right and sprintf('%05d') pads numbers. Padding for display is formatting only: the value is still a string.

PHP 6. Zero padding

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.

Strings and functions

7. Get a file extension and the name without it

pathinfo() splits a path into directory, base name, extension and file name. Lowercase the extension before you compare it, and never trust the extension for security: it says nothing about the real content type, as File Uploads explains.

PHP 7. File extension

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.

8. Username from an e-mail address

Validate with filter_var() first, then take the part before the last @ (the local part can itself contain an @ inside quotes, so use strrpos()).

PHP 8. Username from e-mail

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.

9. Pass by reference

By default PHP passes a copy of a scalar to a function. Put & before the parameter to let the function change the caller's variable. References are powerful and easy to misuse, so use them sparingly (see Parameters and Arguments).

PHP 9. Pass by reference

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. Remove things with preg_replace

preg_replace() is the tool for removals that depend on a pattern: digits, repeated spaces, HTML tags, everything inside brackets. Test patterns on examples like these before you use them on data.

PHP 10. preg_replace removals

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 pattern inserts a comma at every position that has a digit before it and a multiple of three digits after it. For production number formatting use number_format(), and for HTML use strip_tags() or a real parser rather than a regular expression.

11. Age from a birth date

DateTimeImmutable::diff() returns years, months and days correctly, including leap years. Passing a fixed "today" makes the program testable.

PHP 11. Age from a birth date

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.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does a DatePeriod need the end date plus one day to include the end date?

    By default iteration stops before the end date. Adding a day, or using the INCLUDE_END_DATE option, includes it.
  2. 2. Across a daylight-saving change, how does "+24 hours" differ from "+1 day"?

    When clocks change, a calendar day can be 23 or 25 hours long. Hours measure elapsed time; days measure calendar time.
  3. 3. What does the & in "function f(int &$n)" do?

    Without the ampersand the function receives a copy, so assignments inside it do not change the caller's variable.
  4. 4. Why should you lowercase a file extension before comparing it, and never rely on it for security?

    A file named photo.JPG is the same type as photo.jpg, and any file can be given any extension, so validate the actual content as well.

Summary

  • Use DateTimeImmutable with an explicit time zone; DatePeriod excludes its end date by default.
  • modify('last day of this month') and format('t') answer month-length questions.
  • Hours and days are different units across daylight-saving changes.
  • Convert strings to DateTimeImmutable before sorting dates; objects compare with <=>.
  • sprintf() and str_pad() format numbers and text; pathinfo() splits file names.
  • Validate e-mail addresses with filter_var() before slicing them.
  • Use references (&$param) sparingly; preg_replace() handles pattern-based removals.

Next: PHP JSON and File System Programs