Variable Variables
Demonstrates PHP variable variables with an explicit allowlist so the selected variable name is controlled by code, not raw user input.
Purpose
Demonstrates PHP variable variables with an explicit allowlist so the selected variable name is controlled by code, not raw user input.
Snippet details
ContextLanguageLevelProductionCopy-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.
*/
/**
* Variable Variables.
*
* Purpose:
* Demonstrates controlled use of PHP variable variables.
*
* @param string $selected_name Allowed variable name to read.
* @return array Lookup result.
*/
function ogSnippetVariableVariables(string $selected_name): array {
$enterprise_status = 'ready';
$serenity_status = 'flying';
$rocinante_status = 'burning hard';
$allowed_names = array('enterprise_status', 'serenity_status', 'rocinante_status');
$selected_name = trim($selected_name);
$result = array(
'allowed' => false,
'name' => $selected_name,
'value' => ''
);
if (in_array($selected_name, $allowed_names, true) === false) {
return $result;
}
$result['allowed'] = true;
$result['value'] = $$selected_name;
return $result;
}
$status_report = ogSnippetVariableVariables('serenity_status');
echo 'Variable variable value: '.$status_report['value'];