note 87564 deleted from language.variables.variable by cmb
| From: | cmb@php.net | Date: | Sun, 12 Jan 2020 08:33:43 +0000 |
| Subject: | note 87564 deleted from language.variables.variable by cmb | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-213867@lists.php.net to get a copy of this message | ||
Note Submitter: nick at customdesigns dot ca
----
On the topic of variable variables with arrays, I have a simple function that solves the issue. It
works for both indexed and associative arrays, and allows use with superglobals.
<?php
function VariableArray($arr, $string)
{
preg_match_all('/\[([^\]]*)\]/', $string, $arr_matches, PREG_PATTERN_ORDER);
$return = $arr;
foreach($arr_matches[1] as $dimension)
{
$return = $return[$dimension];
}
return $return;
}
$test = array('one' => 'two', 'four' => array(8));
$foo = 'test';
$bar = $$foo;
$baz = "[one]";
$var = VariableArray($bar, $baz); //$var now contains 'two'
$baz = "[four][0]";
$var = VariableArray($bar, $baz); //$var now contains int(8)
?>
You can simply pass in a superglobal as the first argument. Note for associative arrays don't
put quotes inside the square braces unless you adjust the regexp to accept it. I wanted to keep it
simple.