Generating Arrays from Strings without Empty Elements
The explode() function in PHP generates an array of strings by splitting an input string based on a specified substring. However, it can leave empty strings when there are consecutive delimiters. This issue arises when attempting to retrieve distinctive elements.
Solution:
To eliminate empty elements from the resulting array, consider using preg_split(). This function offers more flexibility and control over the splitting process.
Code Snippet:
$exploded = preg_split('@/@', '1/2//3/', -1, PREG_SPLIT_NO_EMPTY);
In this example:
The output will be:
array( [0] => "1", [1] => "2", [2] => "3" )
This method effectively provides an array with only non-empty elements, unlike explode() which includes empty strings.
The above is the detailed content of How Can I Generate a PHP Array from a String Without Empty Elements?. For more information, please follow other related articles on the PHP Chinese website!