Advertisement:
Read Later
In this tutorial, I will show you how to prevent the Undefined Offset 1 error when using the explode() function in PHP. This error occurs due to the undefined array range while reading it. And, the Undefined Offset 1 error can be solved easily by merely adding the selected delimiter at the end of the string in the explode() function.
Syntax(1):
explode ( string $delimiter , string $string [, int $limit = PHP_INT_MAX ] ) : array
Returns an array of strings, each of which is a substring of string formed by splitting it on boundaries formed by the string delimiter.
- delimiter (The boundary string.)
- string (The input string.)
- limit
If limit is set and positive, the returned array will contain a maximum of limit elements with the last element containing the rest of string. If the limit parameter is negative, all components except the last -limit are returned. If the limit parameter is zero, then this is treated as 1.
If delimiter is an empty string (""), explode() will return FALSE. If delimiter contains a value that is not contained in string and a negative limit is used, then an empty array will be returned, otherwise an array containing string will be returned.
- Define a string with to split, consisting of substrings seperated by a delimiter (:).
- Get substrings using the explode() function.
- Add the delimiter (:) at the end of the string in the explode()function - "$string_to_split:".
- Print each substring.
- Define the error string including one substring without the delimiter.
- Print the second substring that of the error string.
- Add the delimiter (:) at the end of the string in the explode()function - "$error_string:".
- Note: In this way, when you are using the explode() function in a function and if it tries to split a string like the error string, the server will not throw the Undefined Offset 1 error.
-------------- PHP --------------
$string_to_split = "Hello:world:php:web:website:developer, :126885682/ ";
$substring = explode(":", "$string_to_split:");
forEach($substring as $line){
echo "<p>".$line."</p>";
}
$error_string = "test error";
echo "<p>".explode(":", "$error_string:")[1]."</p>";
Result:
You can inspect a web application in which I utilized this method from here.
Hello
world
php
web
website
developer,
126885682/
(1) https://www.php.net/manual/en/function.explode.php