Skip to content
← Back to Snippets
Code

Using array_map()

Uses array_map() with a named callback to normalize every string value in an array.

Purpose

Uses array_map() with a named callback to normalize every string value in an array.

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

/**
 * Normalizes a ship name for array_map().
 *
 * @param string $value Raw value.
 * @return string Normalized value.
 */
function ogSnippetArrayMapNormalizeShip(string $value): string {
	return strtoupper(trim($value));
}

/**
 * Using array_map().
 *
 * Purpose:
 * Applies a named callback to every value in an array.
 *
 * @param array $values Raw values.
 * @return array Normalized values.
 */
function ogSnippetUsingArrayMap(array $values): array {
	$strings = array();

	foreach ($values as $value) {
		if (is_scalar($value) === true) {
			$strings[] = (string) $value;
		}
	}

	return array_map('ogSnippetArrayMapNormalizeShip', $strings);
}

$mapped_ships = ogSnippetUsingArrayMap(array(' enterprise ', ' serenity ', ' rocinante '));

echo 'Mapped ship: '.$mapped_ships[0];