Skip to content
Tutorials Center
My learning

Topics

Lesson 31 of 147 ยท Functions

Using Built-in Functions

Learn to use PHP's built-in functions - read manual signatures, know the function families, pass callbacks, handle false returns, avoid deprecated functions and use NoDiscard.

PHP ships with well over a thousand built-in functions, and that's one of its biggest strengths. Sorting, string handling, dates, JSON, hashing, file access, regular expressions: most everyday tasks are one function call away, written in C and fast. The skill isn't memorizing them all. It's knowing how to find the right function, read its signature, and use it correctly, including its edge cases and failure values.

This lesson teaches exactly that: how to read the signature notation used in PHP's documentation and editors, how the function families are organized, how to pass callbacks, how built-ins report failure, which old functions to avoid, and how PHP 8.5's #[\NoDiscard] attribute warns you when you ignore an important return value.

How many functions are there?

The exact number depends on which extensions are installed. You can ask PHP itself:

PHP Counting the functions PHP knows

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 our server this reports 1528 built-in functions, followed by how many start with each prefix. function_exists() and extension_loaded() let code check what's available: intl is not installed here, so the last line prints bool(false). Real projects usually declare the extensions they need in composer.json instead of checking at runtime (see Autoloading and Composer).

Function families

Built-in function names are grouped by prefix or topic. Learning the families tells you where to look:

Family Examples Lesson
Strings strlen, str_replace, str_contains, trim, sprintf String Functions
Multibyte strings mb_strlen, mb_substr, mb_strtoupper Unicode and Multibyte Strings
Arrays array_map, array_filter, sort, in_array, count Array Functions
Regular expressions preg_match, preg_replace, preg_split Regular Expressions
Math round, intdiv, max, random_int Math Functions
Type checks is_int, is_string, is_numeric, gettype Data Types
Dates date, strtotime, mktime (plus the DateTime classes) Dates and Times
Files file_get_contents, fopen, scandir Reading and Writing Files
JSON json_encode, json_decode, json_validate JSON

Not everything is a function: newer APIs are often classes, like DateTimeImmutable, PDO, SplStack or Random\Randomizer. And older naming isn't perfectly consistent. You'll find strpos next to str_contains, and array_search($needle, $haystack) next to strpos($haystack, $needle). Named arguments (see Parameters and Arguments) make that inconsistency much less painful.

Reading a function signature

The PHP manual, your editor's tooltips and this course all describe functions with a signature like this one:

PHP
str_pad(
    string $string,
    int $length,
    string $pad_string = " ",
    int $pad_type = STR_PAD_RIGHT
): string

Read it piece by piece:

  • Parameter types come first (string, int). In strict mode they must match exactly.
  • Parameter names ($string, $length) are the names you use for named arguments: str_pad('5', 3, pad_type: STR_PAD_LEFT).
  • = value marks an optional parameter and shows its default.
  • : string after the list is the return type.

A few more notations you'll meet:

PHP
str_replace(
    array|string $search,
    array|string $replace,
    array|string $subject,
    int &$count = null
): string|array

array_push(array &$array, mixed ...$values): int

strpos(string $haystack, string $needle, int $offset = 0): int|false

usort(array &$array, callable $callback): true
  • A|B is a union type: either is accepted, or either can come back. str_replace returns a string when given a string subject, an array when given an array.
  • &$name means the argument is passed by reference: the function changes your variable (array_push modifies $array; $count receives the number of replacements). You must pass a variable, not a literal.
  • ...$values is variadic: pass as many values as you like.
  • mixed accepts any type.
  • int|false means the function returns false on failure. More on that below.
  • callable expects a function to call back.
  • : true (PHP 8.2 type) means the function always returns true; older docs say bool.

You can also ask PHP for any function's signature with Reflection, which is handy when you have no documentation at hand:

PHP Inspecting a signature with Reflection

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 output lists each parameter, then uses the function twice:

TEXT
str_pad returns string
  Parameter #0 [ <required> string $string ]
  Parameter #1 [ <required> int $length ]
  Parameter #2 [ <optional> string $pad_string = " " ]
  Parameter #3 [ <optional> int $pad_type = STR_PAD_RIGHT ]
000042
  42  |

Reflection is a powerful tool in its own right; frameworks use it heavily. See Reflection.

Values, references and return values

Built-in functions follow one of two styles, and mixing them up is a classic bug:

  • Return a new value and leave the input alone: strtoupper($s), array_reverse($a), trim($s), array_map(...).
  • Modify the argument in place (by reference) and return something else: sort($a) returns true, shuffle($a), array_push($a, ...) returns the new count, preg_match(..., $matches) fills $matches.
PHP In-place vs returning functions

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 output:

TEXT
Mia, adam, Zoe
Mia, Zoe, adam
bool(true)
bool(true)
adam, Mia, Zoe

The default sort compares bytes, so uppercase letters (M, Z) come before lowercase a. Flags like SORT_FLAG_CASE are constants you combine with |; many built-ins accept options this way. When in doubt about which style a function uses, check its signature for &.

Callbacks

Many built-ins take a callable and call it for you: array_map, array_filter, usort, array_walk, preg_replace_callback, spl_autoload_register, and more. You can pass a closure, an arrow function or a first-class callable (all covered in Anonymous Functions and Closures):

PHP Passing callbacks to built-in functions

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 output:

TEXT
Lamp ($39.90) | Chair ($129.50) | Desk ($249.00)
LAMP, CHAIR, DESK
Order 6 desks and 24 chairs

The documentation for each function says what arguments the callback receives and what it must return. usort passes two elements and expects an int; preg_replace_callback passes an array of matches and expects a string.

Checking for false (and other failure values)

Older functions report failure by returning false instead of throwing an exception. The famous trap is strpos(), which returns the position of a match, and that position can be 0:

PHP The strpos zero trap

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 loose check prints the wrong answer because strpos returned 0 (found at the very start), and 0 is falsy. Always compare with === false or !== false when a function's signature says int|false, string|false or array|false. Newer APIs avoid the problem: str_contains returns a plain bool, json_decode(..., flags: JSON_THROW_ON_ERROR) throws an exception, and PDO can be configured to throw on errors.

The @ before file_get_contents hides the warning here only to keep the output short; in real code you'd check is_file() first or handle the error properly (see Errors, Warnings and Notices).

Deprecated and removed functions

PHP removes functions slowly: first it marks them deprecated (they still work but emit a Deprecated: message), then a later major version removes them. Some you'll meet in old tutorials and legacy code:

Function Status Use instead
mysql_* (e.g. mysql_query) removed in 7.0 PDO or mysqli (PHP and Databases)
ereg, split removed in 7.0 preg_match, preg_split
create_function removed in 8.0 closures
each removed in 8.0 foreach
strftime, gmstrftime deprecated in 8.1 date(), DateTimeImmutable::format()
utf8_encode, utf8_decode deprecated in 8.2 mb_convert_encoding()

When you see a deprecation message, treat it as a to-do item: the code will break on a future PHP version.

#[\NoDiscard]: don't ignore the result (PHP 8.5)

Some functions are pointless, or dangerous, to call without using their result. PHP 8.5 adds the #[\NoDiscard] attribute: if code calls such a function and throws the result away, PHP emits a warning. Several built-in methods use it, for example the DateTimeImmutable methods, which return a new object instead of changing the existing one. This example triggers the warning on purpose:

PHP NoDiscard warns about ignored results

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 run shows two warnings, then the dates and the status:

TEXT
Warning: The return value of method DateTimeImmutable::modify() should either be used or intentionally ignored by casting it as (void), as DateTimeImmutable::modify() does not modify the object itself in main.php on line 5
2026-01-15
2026-02-15

Warning: The return value of function prepareOrder() should either be used or intentionally ignored by casting it as (void), the order is not saved until you call save() in main.php on line 17
draft

The optional message explains why the result matters. When you really mean to discard a result, the new (void) cast (also PHP 8.5) says so explicitly and silences the warning. Attributes in general are covered in Attributes.

Tips for working with built-ins

  • Search before you write. Before writing a loop to reverse, pad, split, count or deduplicate, check whether a function already does it. It usually does.
  • Check the return type for |false or |null and handle that case.
  • Check for & parameters; don't assign the result of in-place functions.
  • Use named arguments for flags and long optional lists: json_encode($data, flags: JSON_PRETTY_PRINT).
  • Prefer the modern variant: str_contains over strpos !== false, random_int over rand, DateTimeImmutable over strtotime arithmetic, password_hash over md5.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does int &$count = null in a signature tell you?

    The & means by reference, and = null makes it optional. str_replace uses it to report how many replacements it made.
  2. 2. What does $sorted = sort($list); put in $sorted?

    sort() sorts $list in place and returns true. Use $list itself afterward.
  3. 3. strpos("hello", "he") returns 0. Which check correctly detects "found"?

    0 is a valid position but falsy. Only a strict comparison with false distinguishes "found at 0" from "not found". str_contains() is simpler still.
  4. 4. What does PHP 8.5 do when you call a #[\NoDiscard] function and ignore its result?

    The engine emits a warning at runtime. A (void) cast marks the discard as intentional.

Summary

  • PHP has over 1,500 built-in functions, grouped into families by prefix (str_, array_, mb_, preg_, is_, json_). function_exists() and extension_loaded() check availability.
  • Signatures show types, names (for named arguments), defaults (= value), references (&), variadics (...) and return types. ReflectionFunction prints them too.
  • Some functions return new values; others modify the argument by reference and return true or a count. Don't confuse the two.
  • Callbacks (closures, arrow functions, strtoupper(...)) customize usort, array_map, preg_replace_callback and many more.
  • Functions returning int|false or similar need strict checks like !== false.
  • Avoid deprecated and removed functions such as mysql_*, each, create_function, strftime and utf8_encode.
  • #[\NoDiscard] (8.5) warns when an important result is ignored; (void) discards on purpose.

Next: String Functions