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.
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 .
Laravel Tech Community
Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.