Home >Backend Development >PHP Tutorial >How Can I Generate a PHP Array from a String Without Empty Elements?

How Can I Generate a PHP Array from a String Without Empty Elements?

Linda Hamilton
Linda HamiltonOriginal
2024-11-26 10:12:10255browse

How Can I Generate a PHP Array from a String Without Empty Elements?

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:

  • preg_split() splits the string '1/2//3/' at every occurrence of '/'.
  • -1 indicates that all matches should be split, preventing empty elements.
  • PREG_SPLIT_NO_EMPTY excludes empty elements from the resulting array.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn