Wednesday 16 March 2016

php - How to print the name of a variable and a array?










I'm needding something similar to the code below:



code





$var1='my var 1';

$array1['1']='first position of my array 1';
$array1['2']='second position of my array 1';

echo name($var1);


echo "
";

echo name($array1);

function name($parameter){
...?...
}
?>



screen return



var1
array1


So, I need to write a function that gives me the name of a variable or an array that I pass to it. How can I perform this?



I will use this function on another function to perform some tasks to me...


Answer




As @bfavaretto said,



this worked fine to me:




$var1='my var 1';

$array1['1']='first position of my array 1';
$array1['2']='second position of my array 1';


echo name($var1);

echo "
";

echo name($array1);

function name(&$var, $scope=false, $prefix='unique', $suffix='value'){
if($scope) $vals = $scope;
else $vals = $GLOBALS;

$old = $var;
$var = $new = $prefix.rand().$suffix;
$vname = FALSE;
foreach($vals as $key => $val) {
if($val === $new) $vname = $key;
}
$var = $old;
return $vname;
}
?>


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...