PHP
June 15, 2026

Practical PHP Functions for Numbers, Strings, Dates, Redirects, and Script Control

Introduction

A PHP script becomes useful when it can transform values, format output, make decisions, and stop safely when something goes wrong. Variables and statements give you the structure, but functions give you the practical tools.

A function is a named operation that receives input values, called arguments, and usually returns a value. For example, one function may round a number, another may remove extra spaces from text, and another may return today's date in a specific format.

PHP includes many built-in functions. You do not need to write the logic for every common task yourself. Instead, you can combine small functions to solve everyday problems, such as:

  • Cleaning a name submitted by a user
  • Formatting a date for display
  • Extracting part of a structured string
  • Choosing a random image or message
  • Finding the largest or smallest value in a list
  • Redirecting the browser after a script completes
  • Stopping a script when a required operation fails
  • Checking the PHP configuration used by the server

This post focuses on practical functions useful for writing beginner-friendly PHP scripts for web pages and server-side processing.

Context and Scope

PHP is commonly used as a server-side language. That means the script runs on the web server, not inside the user's browser. When a PHP file is requested, the server executes the PHP code and sends the resulting output to the browser.

The functions covered here fall into these groups:

Function area Practical purpose
Numeric functions Round values, calculate square roots, handle absolute values, work with powers, and process mathematical values
Trigonometric functions Work with angles, especially when calculations require radians
String functions Clean, normalize, replace, reverse, split, join, and extract text
Random number functions Select a random value from a small range
Maximum and minimum functions Find the largest or smallest value from several numbers or an array
Date functions Format the current date and time using format characters
Control functions Redirect the browser, terminate a script, output text, and inspect PHP configuration

The goal is not to memorize every PHP function. The goal is to recognize common situations and know which function can solve each one.

Working with Numbers

PHP includes several functions for common numeric operations. These are useful when you need to clean up calculations before displaying them.

For example, a calculation may produce many decimal places, but the user only needs two. A value may be negative, but you need its absolute size. A square root or power calculation may be needed as part of a formula.

Some useful numeric functions are:

Function What it returns
abs() The absolute value of a number
ceil() The smallest integer greater than or equal to the number
floor() The largest integer less than or equal to the number
round() The number rounded to an integer or a selected number of decimal places
sqrt() The square root of a non-negative number
pow() The first argument raised to the power of the second argument
log() The natural logarithm of the argument
log10() The base 10 logarithm of the argument
exp() The value of e raised to the power of the argument
pi() The value of pi

Here is a small example that shows how several of these functions can be used in ordinary calculations:

<?php
$balanceChange = -48.75;
$rawAverage = 7.46153846154;
$pageSize = 10;
$totalRecords = 93;

print "Absolute change: ".abs($balanceChange)."\n";
print "Rounded average: ".round($rawAverage, 2)."\n";
print "Pages needed: ".ceil($totalRecords / $pageSize)."\n";
print "Whole part only: ".floor($rawAverage)."\n";
print "Two to the power of eight: ".pow(2, 8)."\n";
print "Square root of 144: ".sqrt(144)."\n";
print "Pi from function: ".pi()."\n";
?>

A few practical rules are worth remembering:

  • Use round() when you want a readable value for output.
  • Use ceil() when you need enough whole units to cover something, such as pages or batches.
  • Use floor() when you intentionally want to discard the decimal part by moving down to the nearest integer.
  • Use sqrt() only with non-negative values.
  • Use pow() when an exponent is clearer than repeated multiplication.

PHP also provides the mathematical constant M_PI, which gives another way to access pi. Unlike function names, this constant is case-sensitive.

Working with Angles

PHP has trigonometric functions such as sin(), cos(), and tan(). These are most useful in mathematical scripts. The important detail is that these functions expect angles in radians, not degrees.

If you have a value in degrees, convert it first with deg2rad(). If a function returns a radian value and you need degrees, convert it with rad2deg().

<?php
$angleInDegrees = 45;
$angleInRadians = deg2rad($angleInDegrees);

print "Sine: ".sin($angleInRadians)."\n";
print "Cosine: ".cos($angleInRadians)."\n";
print "Back to degrees: ".rad2deg($angleInRadians)."\n";
?>

The main mistake here is passing degrees directly into sin(), cos(), or tan(). The script will still run, but the result will not mean what you expected.

Cleaning and Normalizing Strings

A string is a sequence of characters, such as a name, message, date, code, or line of structured text. Many web applications receive strings from users, files, or databases. Before comparing or storing text, it is often useful to normalize it.

Removing Extra Whitespace

The trim() function removes spaces, tabs, newline characters, and carriage returns from the start and end of a string.

There are also more specific versions:

  • ltrim() removes leading whitespace from the left side.
  • rtrim() removes trailing whitespace from the right side.
<?php
$submittedUsername = "   alex_dev   ";

$cleanUsername = trim($submittedUsername);
$leftCleaned = ltrim($submittedUsername);
$rightCleaned = rtrim($submittedUsername);

print "Clean username: ".$cleanUsername."\n";
print "Left cleaned: ".$leftCleaned."\n";
print "Right cleaned: ".$rightCleaned."\n";
?>

In practice, trim() is especially useful before comparing user input. Without trimming, the strings "alex_dev" and " alex_dev "` are not the same.

Changing Letter Case

String comparisons can become unreliable when one value uses uppercase letters, and another uses lowercase letters. PHP provides simple functions for case conversion:

Function Result
strtolower() Converts a string to lowercase
strtoupper() Converts a string to uppercase
ucfirst() Converts the first character to uppercase
ucwords() Converts the first character of every word to uppercase
<?php
$rawName = "   mARtin WILSON   ";

$normalized = strtolower(trim($rawName));
$displayName = ucwords($normalized);

print "Stored form: ".$normalized."\n";
print "Display form: ".$displayName."\n";
?>

This pattern is common:

  1. Remove surrounding whitespace with trim().
  2. Convert the value to a consistent storage form with strtolower().
  3. Convert it to a friendly display form with ucfirst() or ucwords() when needed.

Replacing, Reversing, and Extracting Text

Once a string has a predictable structure, PHP can help you manipulate it.

Replacing Part of a String

The str_replace() function replaces every occurrence of one substring with another substring.

<?php
$record = "Tuesday,June,3rd,ella,stone";
$converted = str_replace(",", "**", $record);

print $converted;
?>

The result is the same text with every comma replaced by two asterisks. This is useful when changing separators or cleaning a repeated character pattern.

Reversing a String

The strrev() function returns the characters of a string in reverse order.

<?php
$word = "level";

if ($word == strrev($word)) {
    print "The word reads the same in both directions.";
} else {
    print "The word changes when reversed.";
}
?>

This is a simple way to check whether a string is a palindrome, meaning that it reads the same forward and backward.

Extracting a Fixed Position Substring

The substr() function extracts part of a string. The second argument is the starting position, counted from zero. The third argument is the number of characters to extract.

<?php
$dateCode = "281225";
$yearPart = substr($dateCode, 0, 2);
$monthPart = substr($dateCode, 2, 2);
$dayPart = substr($dateCode, 4, 2);

print "Year: ".$yearPart."\n";
print "Month: ".$monthPart."\n";
print "Day: ".$dayPart."\n";
?>

This works well when every part of the string has a fixed width.

Finding a Separator Before Extracting Text

Sometimes the fields are not fixed-width. In that case, you can find the separator first.

The strpos() function returns the position of the first occurrence of a substring. The strrpos() function returns the position of the last occurrence. The strlen() function returns the length of a string.

<?php
$label = "Monday**April**7th";

$firstSeparator = strpos($label, "**");
$weekday = substr($label, 0, $firstSeparator);

$lastSeparator = strrpos($label, "**");
$day = substr($label, $lastSeparator + 2, strlen($label) - $lastSeparator - 2);

print "Weekday: ".$weekday."\n";
print "Day: ".$day."\n";
?>

This approach is useful when a string contains fields separated by a known marker.

Splitting and Joining Structured Strings

When text contains repeated separators, extracting fields with substr() can become clumsy. The explode() function is often cleaner.

explode() converts a string into an array. It takes a separator as its first argument and the full string as its second argument.

<?php
$employeeLine = "nora**kent**designer**london**46";
$parts = explode("**", $employeeLine);

print "First name: ".$parts[0]."\n";
print "Last name: ".$parts[1]."\n";
print "Role: ".$parts[2]."\n";
print "City: ".$parts[3]."\n";
print "Age: ".$parts[4]."\n";
?>

The opposite operation is done with implode(). It takes an array and joins its values into a string using a selected separator.

<?php
$parts = array("nora", "kent", "designer", "london", "46");
$line = implode("|", $parts);

print $line;
?>

The separator does not have to be a single character. It can be any string. Escape sequences such as \n, \r, or \t can also be used when appropriate.

Limiting explode Results

explode() can also take a third argument that limits the result.

If the third argument is positive, the returned array contains at most that many elements. The final element contains the remaining part of the string.

If it is negative, PHP returns all components except the last number of components indicated by the negative value.

If it is zero, it behaves like one.

<?php
$entry = "john**smith**male**builder**paris**39";

$firstThree = explode("**", $entry, 3);
$withoutLastTwo = explode("**", $entry, -2);
$singlePart = explode("**", $entry, 0);

print "Limited final part: ".$firstThree[2]."\n";
print "Fourth kept value: ".$withoutLastTwo[3]."\n";
print "Single returned value: ".$singlePart[0]."\n";
?>

This is helpful when only part of a structured string should be processed.

Wrapping Long Text

The wordwrap() function breaks a long string into shorter pieces. It takes three arguments:

  1. The original string
  2. The maximum line width
  3. The separator to insert at wrap points
<?php
$message = "The time has come to review the report and prepare the next update";
$wrapped = wordwrap($message, 18, "\n");

print $wrapped;
?>

The wrap width is a maximum. Lines may be shorter because PHP avoids splitting in the middle of a word when it can wrap at a space.

This is useful when displaying long text in a narrow area or preparing readable plain text output.

Random Selection with rand

The rand() function returns a random integer between two provided integer arguments, including both endpoints.

For example, rand(1, 7) can return any integer from 1 through 7.

A practical use is choosing one value from a small list.

<?php
$messages = array("Welcome back", "Good to see you", "Ready to continue");
$selectedIndex = rand(0, 2);

print $messages[$selectedIndex];
?>

You can also combine random letters and digits for simple generated values in learning exercises or low-risk display examples.

<?php
$letters = "abcdefghijklmnopqrstuvwxyz";

$code = substr($letters, rand(0, 25), 1)
    .substr($letters, rand(0, 25), 1)
    .substr($letters, rand(0, 25), 1)
    .rand(1000, 9999);

print $code;
?>

The substr() calls choose individual letters from the alphabet string. The final rand() call appends four digits.

Finding Maximum and Minimum Values

PHP provides max() and min() for finding the largest and smallest values.

They can be used with several arguments:

<?php
print "Highest: ".max(34.2, -8.2, 27.3, 0, 55.91)."\n";
print "Lowest: ".min(34.2, -8.2, 27.3, 0, 55.91)."\n";
?>

They can also receive a single array argument:

<?php
$scores = array(34.2, -8.2, 27.3, 0, 55.91);

print "Highest score: ".max($scores)."\n";
print "Lowest score: ".min($scores)."\n";
?>

This keeps the code readable when the number of values is not convenient to write as separate arguments.

Formatting Dates and Times

The date() function returns a string based on the current system date and time. It takes one argument: a format string.

Each special character in the format string represents one part of the date or time. Characters without a special meaning are returned as themselves, which makes separators easy to add.

Common date format characters include:

Character Meaning Example style
d Day of the month with leading zero 01 to 31
j Day of the month without leading zero 1 to 31
m Month number with leading zero 01 to 12
n Month number without leading zero 1 to 12
F Full month name January
M Short month name Jan
Y Four-digit year 2028
y Two-digit year 28
l Full weekday name Monday
D Short weekday name Mon
S English suffix for day number st, nd, rd, or th

Common time format characters include:

Character Meaning
g 12-hour format without leading zero
h 12-hour format with leading zero
G 24-hour format without leading zero
H 24-hour format with leading zero
i Minutes with leading zero
s Seconds with leading zero
a Lowercase am or pm
A Uppercase AM or PM

Here are several examples:

<?php
print date("Y-m-d")."\n";
print date("d F Y")."\n";
print date("l F jS")."\n";
print date("g:i a")."\n";
?>

A format such as "Y-m-d" works because Y, m, and d have special meanings, while the hyphen is returned as a normal character.

You can also use date() in conditions.

<?php
$leapValue = date("L");

if ($leapValue == 1) {
    print "The current year is a leap year.";
} else {
    print "The current year is not a leap year.";
}
?>

The format character L returns 1 when the current year is a leap year and 0 otherwise.

Another useful pattern is checking the current day of the week:

<?php
$shortDay = date("D");

if ($shortDay == "Sat") {
    print "Weekend: Saturday";
} elseif ($shortDay == "Sun") {
    print "Weekend: Sunday";
} else {
    print "Weekday";
}
?>

The practical lesson is that date() is not only for display. It can also drive simple decisions.

Redirecting with header

The header() function sends an HTTP header to the browser. A very useful case is redirecting the browser to another page after a script has finished its work.

<?php
$saveCompleted = true;

if (!$saveCompleted) {
    die("The operation could not be completed.");
}

header("Location: finished.php");
?>

The important rule is that the header must be sent before any output is sent to the browser. That means no printed text, no blank output, and no earlier generated content before header() runs.

A redirect is useful after operations such as updating a file, completing a form step, or moving the user to a result page.

Stopping Execution with die

The die() function outputs a message and immediately terminates the script.

<?php
$canContinue = false;

if (!$canContinue) {
    die("Required data was not available.");
}

print "This line will not run when the condition fails.";
?>

This is useful when continuing would cause more problems than stopping. For example, if a script depends on data that could not be loaded, it is usually better to terminate than to keep processing invalid values.

print, echo, and Standalone Functions

PHP has a print statement for sending output. It also has echo, which can be used in a very similar way.

<?php
$name = "Lena";
$count = 4;

print "Name: ".$name."\n";
echo("Count: ".$count."\n");
?>

For many beginner-level scripts, print and echo can be treated as effectively equivalent for output. The main thing is to keep output readable and intentional.

Some functions are commonly used for their action rather than for a value assigned to a variable. For example, header() sends a header, die() stops execution, and phpinfo() outputs configuration information. These can be thought of as standalone function calls because they are useful even when you do not assign their return value to a variable.

Inspecting PHP Configuration with phpinfo

The phpinfo() function outputs detailed information about the PHP configuration used by the server, including the PHP version.

<?php
phpinfo();
?>

The function takes no arguments. It is normally used as a standalone call because the useful result is the information it outputs.

This is helpful when you need to confirm which PHP setup is running before debugging behavior that depends on the environment.

A Practical Mini Workflow

The following example combines several functions into one practical flow. It cleans a submitted name, formats the current date, creates a simple reference code, and stops if the cleaned name is empty.

<?php
$rawName = "   jANE smith   ";

$cleanName = trim($rawName);

if ($cleanName == "") {
    die("A name is required.");
}

$displayName = ucwords(strtolower($cleanName));
$today = date("Y-m-d");
$letters = "abcdefghijklmnopqrstuvwxyz";
$reference = substr($letters, rand(0, 25), 1).rand(1000, 9999);

print "Name: ".$displayName."\n";
print "Date: ".$today."\n";
print "Reference: ".$reference."\n";
?>

This example shows an important habit: functions become more powerful when combined carefully. Each function performs one small job, making the script a readable workflow.

Common Mistakes to Watch For

Treating Raw User Text as Already Clean

User input often contains extra spaces or inconsistent capitalization. Use trim() and case conversion functions before comparing values.

Passing Degrees Directly to Trigonometric Functions

Functions such as sin(), cos(), and tan() expect radians. Use deg2rad() first when your value is in degrees.

Forgetting That String Positions Start at Zero

substr(), strpos(), and related functions use zero-based positions. The first character is position 0, not position 1.

Using the Wrong Separator with explode

explode() only works correctly when the separator matches the string. If the data uses "**", splitting on "*" changes the meaning.

Sending Output Before header

A redirect using header() must happen before output is sent to the browser. Keep redirect logic at the top of the script or before anything is printed.

Continuing After a Fatal Missing Requirement

If required data is missing, use a clear stop point. die() can prevent the script from continuing with invalid assumptions.

Checklist

Use this checklist when choosing a PHP function:

  • Need to remove spaces around user input? Use trim().
  • Need consistent lowercase or uppercase text? Use strtolower() or strtoupper().
  • Need friendly display capitalization? Use ucfirst() or ucwords().
  • Need to replace every occurrence of a substring? Use str_replace().
  • Need part of a fixed-width string? Use substr().
  • Need to locate a separator? Use strpos() or strrpos().
  • Need to split structured text into fields? Use explode().
  • Need to join fields back into text? Use implode().
  • Need readable long text? Use wordwrap().
  • Need a rounded number? Use round().
  • Need the highest or lowest value? Use max() or min().
  • Need today's date or time? Use date() with a format string.
  • Need a browser redirect? Use header() before output.
  • Need to stop the script immediately? Use die().
  • Need PHP environment details? Use phpinfo().

Conclusion

PHP's built-in functions are small tools that solve common problems. Numeric functions make calculations presentable. String functions make text reliable. Date functions make time-based output flexible. Control functions such as header() and die() help manage what happens after a script runs.

The best way to learn these functions is to use them in simple workflows: clean input, transform values, format output, and handle failure early. Once these patterns become familiar, PHP scripts become much easier to read, test, and extend.

Share:

Comments0

Home Profile Menu Sidebar
Top