PHP Built-in Functions Reference

Navigate PHP function families, read signatures and choose predictable APIs for strings, arrays, dates and data.

Lesson 35 of 86Beginner9 min read

PHP includes many functions for common work: trimming text, sorting arrays, formatting dates, encoding JSON and inspecting values. You do not need to memorize all of them. The practical skill is recognizing the relevant family, reading a function's contract and checking what happens for missing, malformed or unsupported input.

This reference gives you a map and a repeatable way to evaluate a function before using it. The examples focus on small, predictable transformations rather than a giant alphabetical list. For more detail in an established area, continue with array functions, strings or date and time.

Read a function signature as a contract

A signature tells you the parameter order, accepted types, optional arguments and return type. A default value means you may omit that argument. A return type such as int|false means failure is a distinct possible result, not merely another successful number. The description and notes explain details that the short signature cannot express.

Look for whether the function changes an input. sort() modifies the array passed to it, while array_map() returns a transformed array. A name alone does not tell you which behavior occurs. A function returning a success boolean is not necessarily returning the transformed data, so assigning that result back to your original array can replace the array with true or false.

Check warnings, exceptions and version notes. Older examples may rely on permissive coercions that modern PHP rejects. A function may also require an extension, such as mbstring for many Unicode-aware string operations. Confirm availability in the deployed environment rather than only in your editor or command-line installation.

Strings: bytes, characters and safe output

trim() removes selected characters from the ends of a string. strlen() counts bytes, not necessarily user-perceived characters. str_contains() and str_starts_with() provide clear substring checks in PHP 8. explode() splits text by a delimiter, while implode() joins array values with a delimiter.

Unicode text requires care. A multibyte character can occupy several bytes, and even a Unicode code-point count can differ from a visible grapheme count. Use the appropriate mbstring or intl API when the requirement is based on human-visible characters. Do not blindly shorten a UTF-8 string by byte position if that can cut a character in half.

htmlspecialchars() prepares text for an HTML context. It is not a general sanitizer for SQL, JavaScript or file paths. Prepared statements protect query values; JSON encoding constructs JSON; a path allowlist controls file selection. Choose a function based on the destination context instead of searching for one universal escape function.

Arrays and value inspection

count() returns the number of elements in an array or a Countable object. array_keys() extracts keys, and array_values() extracts values with consecutive numeric keys. in_array() searches values; use its strict mode when confusing numbers and numeric strings would be a problem. array_key_exists() checks keys and differs from isset for null values.

array_filter() keeps entries whose callback accepts them and preserves keys. Without a callback it removes false-like values, which may discard valid zeros. array_map() transforms values. array_reduce() accumulates a result, but a straightforward loop can be easier to read for stateful or complex calculations.

For inspection, get_debug_type() provides useful type names in modern PHP, while var_export() gives a readable representation of a value. var_dump() includes type and value information. Keep these diagnostic tools out of public responses when the inspected data may include credentials, personal information or internal paths.

Dates, numbers and structured data

Math functions such as abs(), ceil(), floor() and round() solve different numeric questions. A rounding policy should be chosen from the domain requirement. number_format() produces presentation text and should not become the source for later arithmetic. For exact amounts, use an appropriate representation such as integer cents.

For dates, the DateTimeImmutable class provides an object-oriented alternative to functions such as date() and strtotime(). Always make the intended timezone clear. A relative date parser is convenient for trusted phrases, but an API accepting one exact date format should parse and validate that format deliberately.

json_encode() and json_decode() connect PHP values with JSON. Use JSON_THROW_ON_ERROR when exceptions fit your error-handling approach. A successful decode does not validate the structure of the result. Check the required keys, types and limits before using decoded data as an order, account or configuration object.

PHP Built-in Functions Reference Examples

Each example shows the code, the output it produces and what each part does.

Example 1

Normalize and join a short label list

The callback name tells array_map to trim each item. The transformation returns a new array, which is stored in $clean. The original input remains available. This composition is clear because each function performs one small operation with a simple contract.

PHP
<?php
$raw = ['  blue ', 'green  ', ' red'];
$clean = array_map('trim', $raw);
echo implode(' | ', $clean) . PHP_EOL;
echo str_contains($clean[0], 'bl') ? 'found' : 'missing';
echo PHP_EOL;
Output
blue | green | red
found

Common PHP Built-in Functions Reference Mistakes

Treating return values as automatic success

Some APIs return false, some throw, some emit warnings and some return an empty result that is still successful. Read the documented failure contract before writing a condition. A search position of zero is a classic example: it means found at the beginning, so comparing loosely with false can report failure incorrectly.

Do not call a function simply because its name came from a request parameter. Dynamic invocation of arbitrary built-ins exposes capabilities the endpoint never intended to offer. Map approved operation names to specific handlers. The PHP function reference is the authoritative directory, and each individual page supplies extension requirements and version notes.

PHP Built-in Functions Reference in Real Projects

Practical task: clean a comma-separated tag field

Turn the text php, , sql,php into a list of nonblank unique tags. Split on commas, trim every item, remove only empty strings, remove duplicates and rebuild list keys. This is a narrow text-format task; it is not a full CSV parser, because quoted delimiters require proper CSV handling.

PHP
<?php
$input = 'php, , sql,php';
$tags = array_map('trim', explode(',', $input));
$tags = array_filter($tags, fn(string $tag): bool => $tag !== '');
$tags = array_values(array_unique($tags));
echo json_encode($tags, JSON_THROW_ON_ERROR) . PHP_EOL;
Output
["php","sql"]

The explicit filter avoids removing the valid tag '0'. Deduplication retains the first occurrence of each tag, and array_values makes the final value a list for JSON. Try input containing uppercase PHP and decide whether your product treats it as a separate tag. Add normalization only when the requirement calls for it; case folding is a domain decision.

PHP Built-in Functions Reference FAQ

How do I find a function I do not know?

Start with the data type or task family, then read the official entry's signature, return values, errors and examples. Searching by the intended result is more useful than guessing a name.

Does function_exists prove a feature is usable?

It checks whether a function name is defined. Configuration, permissions, input limits and external services can still prevent the intended operation.

Should I write my own trim or JSON parser?

Usually use the established API. Write domain validation around it rather than reproducing a low-level parser without a clear reason.

Are functions and language constructs identical?

No. Constructs such as isset and empty have special language behavior. Their documentation belongs in the same learning toolkit, but they are not ordinary callable functions.

What should I memorize?

Memorize common families and the need to inspect contracts. Precise parameter order and unusual edge cases can be looked up when you use an API.

PHP Built-in Functions Reference Exercises

Answer each one and check it instantly. If you get stuck, open the hint before the answer.

Multiple choiceeasy

Which is the best first check before using an unfamiliar built-in function?

PHP Built-in Functions Reference Quiz

2 questions to check what you learned.

  1. Which function joins array values into a string with a separator?

    • explode()
    • implode()
    • count()
  2. Why can a default array_filter() remove a value you wanted to keep?

    • It always sorts descending
    • It changes every value to text
    • It removes false-like values, including zero