Skip to content
← Back to Snippets
Code

Create a Simple Function

Creates a small reusable PHP function with typed parameters, explicit validation, predictable return data, and a clear example call.

Purpose

Creates a small reusable PHP function with typed parameters, explicit validation, predictable return data, and a clear example call.

Snippet details

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

/**
 * Create a Simple Function.
 *
 * Purpose:
 * Demonstrates a focused function that accepts input, validates it, and returns
 * a predictable value instead of echoing from inside the helper.
 *
 * @param string $ship_name Ship or station label.
 * @param int $crew_count Number of active crew members.
 * @return array Cleaned manifest summary.
 */
function ogSnippetCreateASimpleFunction(string $ship_name, int $crew_count): array {
	$ship_name = trim($ship_name);

	if ($ship_name === '') {
		$ship_name = 'Unnamed vessel';
	}

	if ($crew_count < 0) {
		$crew_count = 0;
	}

	$status = 'standby';
	if ($crew_count > 0) {
		$status = 'active';
	}

	return array(
		'ship_name' => $ship_name,
		'crew_count' => $crew_count,
		'status' => $status,
		'summary' => $ship_name.' crew status: '.$status.' with '.$crew_count.' assigned.'
	);
}

$manifest = ogSnippetCreateASimpleFunction('USS Voyager', 153);

echo $manifest['summary'];