Skip to content
← Back to Snippets
Code

Implode an Array into a String

Joins scalar array values into one string after trimming and skipping empty entries.

Purpose

Joins scalar array values into one string after trimming and skipping empty entries.

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.
 */

/**
 * Implode an Array into a String.
 *
 * Purpose:
 * Cleans array values and joins them with a delimiter.
 *
 * @param array $values Values to join.
 * @param string $delimiter Delimiter to place between values.
 * @return string Joined string.
 */
function ogSnippetImplodeArrayIntoString(array $values, string $delimiter): string {
	$clean_values = array();

	foreach ($values as $value) {
		if (is_scalar($value) === false) {
			continue;
		}

		$clean_value = trim((string) $value);

		if ($clean_value !== '') {
			$clean_values[] = $clean_value;
		}
	}

	return implode($delimiter, $clean_values);
}

$route = ogSnippetImplodeArrayIntoString(array('Earth', 'Mars', 'Ceres'), ' -> ');

echo 'Expanse route: '.$route;