note 87564 added to language.variables.variable

From: Date: Wed, 10 Dec 2008 18:14:40 +0000
Subject: note 87564 added to language.variables.variable
Groups: php.notes 
Request: Send a blank email to php-notes+get-148002@lists.php.net to get a copy of this message
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. 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. ---- Server IP: 66.207.199.35 Probable Submitter: 68.144.188.69 ---- Manual Page -- http://www.php.net/manual/en/language.variables.variable.php Edit -- https://master.php.net/note/edit/87564 Del: integrated -- https://master.php.net/note/delete/87564/integrated Del: useless -- https://master.php.net/note/delete/87564/useless Del: bad code -- https://master.php.net/note/delete/87564/bad+code Del: spam -- https://master.php.net/note/delete/87564/spam Del: non-english -- https://master.php.net/note/delete/87564/non-english Del: in docs -- https://master.php.net/note/delete/87564/in+docs Del: other reasons-- https://master.php.net/note/delete/87564 Reject -- https://master.php.net/note/reject/87564 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#148002) next »