What potential pitfalls should be considered when manipulating strings in PHP, such as substrings and concatenation?
One potential pitfall when manipulating strings in PHP is ensuring that you handle edge cases where the string may be empty or shorter than expected when using functions like substr() or concatenation. To avoid errors, always check the length of the string before manipulating it to prevent out-of-bounds errors or unexpected behavior.
// Check if the string is not empty before manipulating it
$string = "Hello, World!";
if (!empty($string)) {
// Perform string manipulation safely
$substring = substr($string, 0, 5);
$newString = $string . " Welcome!";
// Output the results
echo $substring . PHP_EOL;
echo $newString . PHP_EOL;
} else {
echo "String is empty!";
}