Explode a String into an Array
Splits a delimited string into a cleaned array of non-empty values.
Purpose
Splits a delimited string into a cleaned array of non-empty values.
Snippet details
ContextString ArrayLevelProductionCopy-and-paste statusMarked safe after review.Categories
- Forms and Validation
Code
<?php
/*
* Copyright (c) 2026 Jeffery L. Paris <jparis@phpog.com>.
* Free for personal and internal use. Paid project use requires visible credit
* to Jeffery L. Paris. Corporate use requires a paid license fee unless a
* separate written license states otherwise.
*/
/**
* Explode a String into an Array.
*
* Purpose:
* Splits a delimited string and trims each resulting part.
*
* @param string $text Delimited source text.
* @param string $delimiter Delimiter string.
* @return array Cleaned parts.
*/
function ogSnippetExplodeStringIntoArray(string $text, string $delimiter): array {
$parts = array();
if ($delimiter === '') {
return $parts;
}
$raw_parts = explode($delimiter, $text);
foreach ($raw_parts as $raw_part) {
$part = trim($raw_part);
if ($part !== '') {
$parts[] = $part;
}
}
return $parts;
}
$crew = ogSnippetExplodeStringIntoArray('Kirk, Spock, McCoy', ',');
echo 'Crew count: '.count($crew);