PHP substr() Function – Description, Parameters, Return Value, and Usage Examples

This article explains PHP's substr() function, detailing its purpose, parameter rules, return values, and provides multiple code examples demonstrating positive, negative, and omitted start/length arguments as well as character access via indexing.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
PHP substr() Function – Description, Parameters, Return Value, and Usage Examples

Function: substr() returns a portion of a string based on the supplied start position and optional length.

Parameters: string $string – the input string (must contain at least one character). int $start – if non‑negative, the extraction begins at this zero‑based index; if negative, counting starts from the end of the string. If the absolute value exceeds the string length, FALSE is returned. int $length (optional) – when positive, limits the number of characters returned; when negative, characters are omitted from the end of the string; when zero, FALSE, NULL, or 0, an empty string is returned. If omitted, extraction continues to the end of the string.

Return value: the extracted substring, or FALSE on failure.

Examples:

Example 1 – negative start values:

<?php
$rest = substr("abcdef", -1); // returns "f"
$rest = substr("abcdef", -2); // returns "ef"
$rest = substr("abcdef", -3, 1); // returns "d"
?>

Example 2 – mixed start and length values:

<?php
$rest = substr("abcdef", 0, -1); // returns "abcde"
$rest = substr("abcdef", 2, -1); // returns "cde"
$rest = substr("abcdef", 4, -4); // returns "" (empty string)
?>

Example 3 – using the function in echo statements:

<?php
echo substr('abcdef', 1); // outputs "bcdef"
echo substr('abcdef', 1, 3); // outputs "bcd"
echo substr('abcdef', 0, 4); // outputs "abcd"
echo substr('abcdef', -1, 1); // outputs "f"
?>

Additional note: individual characters can be accessed directly using array‑style indexing, e.g., $string = 'abcdef'; echo $string[0]; // a or echo $string[strlen($string)-1]; // f.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

backend-developmentPHPfunctionexampleString Manipulationsubstr
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.