Skip to content
← Back to Snippets
Code

Sticky Form Value Builder

Builds render-safe sticky form values from submitted input and default values after validation errors.

Purpose

Builds render-safe sticky form values from submitted input and default values after validation errors.

Snippet details

ContextFormLevelAdvancedCopy-and-paste statusMarked safe after review.

Categories

  • Security

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

/**
 * Sticky Form Value Builder.
 *
 * Purpose:
 * Builds render-safe sticky form values from submitted input and default values after validation errors.
 *
 * @param array $submitted Submitted form input.
 * @param array $defaults Default values.
 * @param array $allowed_fields Allowed field names.
 * @return array Render-safe sticky values.
 */
function ogSnippetStickyFormValueBuilder(array $submitted, array $defaults, array $allowed_fields): array {
	$values = array();
	foreach ($allowed_fields as $field) {
		$value = '';
		if (array_key_exists($field, $defaults)) {
			$value = $defaults[$field];
		}
		if (array_key_exists($field, $submitted)) {
			$value = $submitted[$field];
		}
		$values[$field] = htmlspecialchars((string) $value, ENT_QUOTES, 'UTF-8');
	}
	return $values;
}

$sticky = ogSnippetStickyFormValueBuilder(array('ship' => 'Serenity'), array('ship' => 'Rocinante'), array('ship'));
echo $sticky['ship'];