Skip to content
PHP Logo

In the provided code snippet, what is the purpose of using substr() function and how does it contribute to the memory error?

The issue with the code snippet is that the substr() function is being used incorrectly, causing a memory error. The substr() function is used to extract a portion of a string, but in this case, it is being used with an incorrect length parameter, which can lead to excessive memory usage and potentially trigger a memory error. To solve this issue, the length parameter of the substr() function should be adjusted to ensure that it is within the bounds of the string.

php
// Incorrect usage of substr() causing memory error
$longString = "This is a long string that may cause memory error";
$substring = substr($longString, 0, 1000); // Incorrect length parameter

// Corrected usage of substr() to prevent memory error
$correctedSubstring = substr($longString, 0, min(strlen($longString), 100)); // Adjusted length parameter
echo $correctedSubstring;