Skip to content
← Back to Snippets
Code

Add Element to an Array

Adds a trimmed scalar value to an array only when the value is not empty.

Purpose

Adds a trimmed scalar value to an array only when the value is not empty.

Snippet details

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

/**
 * Add Element to an Array.
 *
 * Purpose:
 * Appends a cleaned value to an array.
 *
 * @param array $values Existing values.
 * @param string $new_value Value to append.
 * @return array Updated array.
 */
function ogSnippetAddElementToArray(array $values, string $new_value): array {
	$new_value = trim($new_value);

	if ($new_value !== '') {
		$values[] = $new_value;
	}

	return $values;
}

$gate_teams = array('SG-1', 'SG-3');
$gate_teams = ogSnippetAddElementToArray($gate_teams, 'SG-5');

echo 'Team count: '.count($gate_teams);