This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to get a variable name as a string in PHP?
Example:
Can something like this be achieved in PHP?
$Age = 43;
output_variable_name_and_value($Age);
/*
outputs:
"The requested variable name is Age and its current value is 43";
*/
//If possible, how would the line marked below with ? ? ? ? be?
function output__variable_name_and_value($input)
{
$var_name = get_name_somehow($input); // ? ? ? ?
echo "The requested variable name is {$var_name}
and its current value is {$input}";
}
This is not possible, easily. You have to use $GLOBALS;
function get_variable_name($var) {
foreach($GLOBALS as $k => $v) {
if ($v === $var) {
return $k;
}
}
return false;
}
The only downfall is, it may return a different variable name if they both have the same value.
Or this,
function varName( $v ) {
$trace = debug_backtrace();
$vLine = file( __FILE__ );
$fLine = $vLine[ $trace[0]['line'] - 1 ];
preg_match( "#\\$(\w+)#", $fLine, $match );
print_r( $match );
}
which I found here: How to get a variable name as a string in PHP?
You can use this function:
function var_name(&$iVar, &$aDefinedVars) {
foreach ($aDefinedVars as $k=>$v)
$aDefinedVars_0[$k] = $v;
$iVarSave = $iVar;
$iVar =!$iVar;
$aDiffKeys = array_keys (array_diff_assoc ($aDefinedVars_0, $aDefinedVars));
$iVar = $iVarSave;
return $aDiffKeys[0];
}
Call it like this:
var_name($Age, get_defined_vars());
Source: http://mach13.com/how-to-get-a-variable-name-as-a-string-in-php
Well..
You can figure out what called the output__variable_name_and_value function using debug_backtrace.
Then you know a filename and line number, so you could try to parse the sourcefile and figure out whats between output__variable_name_and_value( and ).
Probably a bad idea though!
Related
I am creating a script that will locate a field in a text file and get the value that I need.
First used the file() function to load my txt into an array by line.
Then I use explode() to create an array for the strings on a selected line.
I assign labels to the array's to describe a $Key and a $Value.
$line = file($myFile);
$arg = 3
$c = explode(" ", $line[$arg]);
$key = strtolower($c[0]);
if (strpos($c[2], '~') !== false) {
$val = str_replace('~', '.', $c[2]);
}else{
$val = $c[2];
}
This works fine but that is a lot of code to have to do over and over again for everything I want to get out of the txt file. So I wanted to create a function that I could call with an argument that would return the value of $key and $val. And this is where I am failing:
<?php
/**
* #author Jason Moore
* #copyright 2014
*/
global $line;
$key = '';
$val = '';
$myFile = "player.txt";
$line = file($myFile); //file in to an array
$arg = 3;
$Character_Name = 3
function get_plr_data2($arg){
global $key;
global $val;
$c = explode(" ", $line[$arg]);
$key = strtolower($c[0]);
if (strpos($c[2], '~') !== false) {
$val = str_replace('~', '.', $c[2]);
}else{
$val = $c[2];
}
return;
}
get_plr_data2($Character_Name);
echo "This character's ",$key,' is ',$val;
?>
I thought that I covered the scope with setting the values in the main and then setting them a global within the function. I feel like I am close but I am just missing something.
I feel like there should be something like return $key,$val; but that doesn't work. I could return an Array but then I would end up typing just as much code to the the info out of the array.
I am missing something with the function and the function argument to. I would like to pass and argument example : get_plr_data2($Character_Name); the argument identifies the line that we are getting the data from.
Any help with this would be more than appreciated.
::Updated::
Thanks to the answers I got past passing the Array.
But my problem is depending on the arguments I put in get_plr_data2($arg) the number of values differ.
I figured that I could just set the Max of num values I could get but this doesn't work at all of course because I end up with undefined offsets instead.
$a = $cdata[0];$b = $cdata[1];$c = $cdata[2];
$d = $cdata[3];$e = $cdata[4];$f = $cdata[5];
$g = $cdata[6];$h = $cdata[7];$i = $cdata[8];
$j = $cdata[9];$k = $cdata[10];$l = $cdata[11];
return array($a,$b,$c,$d,$e,$f,$g,$h,$i,$j,$k,$l);
Now I am thinking that I can use the count function myCount = count($c); to either amend or add more values creating the offsets I need. Or a better option is if there was a way I could generate the return array(), so that it would could the number of values given for array and return all the values needed. I think that maybe I am just making this a whole lot more difficult than it is.
Thanks again for all the help and suggestions
function get_plr_data2($arg){
$myFile = "player.txt";
$line = file($myFile); //file in to an array
$c = explode(" ", $line[$arg]);
$key = strtolower($c[0]);
if (strpos($c[2], '~') !== false) {
$val = str_replace('~', '.', $c[2]);
}else{
$val = $c[2];
}
return array($key,$val);
}
Using:
list($key,$val) = get_plr_data2(SOME_ARG);
you can do this in 2 way
you can return both values in an array
function get_plr_data2($arg){
/* do what you have to do */
$output=array();
$output['key'] =$key;
$output['value']= $value;
return $output;
}
and use the array in your main function
you can use reference so that you can return multiple values
function get_plr_data2($arg,&$key,&$val){
/* do job */
}
//use the function as
$key='';
$val='';
get_plr_data2($arg,$key,$val);
what ever you do to $key in function it will affect the main functions $key
I was over thinking it. Thanks for all they help guys. this is what I finally came up with thanks to your guidance:
<?php
$ch_file = "Thor";
$ch_name = 3;
$ch_lvl = 4;
$ch_clss = 15;
list($a,$b)= get_char($ch_file,$ch_name);//
Echo $a,': ',$b; // Out Puts values from the $cdata array.
function get_char($file,$data){
$myFile = $file.".txt";
$line = file($myFile);
$cdata = preg_split('/\s+/', trim($line[$data]));
return $cdata;
}
Brand new to this community, thanks for all the patience.
This question already has answers here:
In PHP, what does the ${$ } syntax do?
(3 answers)
Closed 9 years ago.
I am new to PHP so please i am sorry if this question is a noob. I don't know its name so couldn't find it. I read it in this piece of code. What does it mean?
Line 5: ${$key}
<?php
$expected = array( 'carModel', 'year', 'bodyStyle' );
foreach( $expected AS $key ) {
if ( !empty( $_POST[ $key ] ) ) {
${$key} = $_POST[ $key ];
} else {
${$key} = NULL;
}
}
?>
This is the same as $$key and means a var named $key
i.e.
$test = "foo";
is the same as
$a = "test";
$$a = "foo";
It's a variable variable. Please read more here: http://php.net/manual/en/language.variables.variable.php
The notation ${$key} is an alternative writing style to simply $$key which is used for variable variables.
One particular case in which you could use that notation is when you do tricks like this:
$var = 'foo_x';
$key = 'x';
${'foo_' . $x} = 'hello';
echo $foo_x; // hello
Set variable with name $key.
$var = NULL;
$name = 'var';
${$name} = TRUE;
var_dump($var); // TRUE
As well as:
$$name = TRUE;
It is a way to use dynmaic variable names. See here: http://php.net/manual/en/language.variables.variable.php
It allows for the use of complex expressions.
It's called complex (curly) syntax, you can find more information at http://php.net/manual/en/language.types.string.php#language.types.string.parsing.complex
I have a recursive array depth of which is variable, and I want to be able to take a string with a separator and convert that string to an index in that array,
For example
$path = 'level1.level2.level3';
will be converted to get the value 'my data' from the array below
$data['level1']['level2']['level3'] = 'my data';
I thought the quickest way to get this would be to use variable variables, but when I try the following code
$index = "data['level1']['level2']['level3']";
echo $$index;
I get the follwing error
PHP Notice: Undefined variable: data['level1']['level2']['level3']
All other ways I can think of doing this are very inefficient, could someone please shed some light on this, is it possible using variable variables for arrays in PHP? Any other efficient workaround?
Many thanks.
You'll have to loop the array, you won't manage to do this using variable variables, as far as I know. This seems to work though:
<?php
function retrieve( $array, $path ) {
$current = $array;
foreach( explode( '.', $path ) as $segment ) {
if( false === array_key_exists( $segment, $current ) ) {
return false;
}
$current = $current[$segment];
}
return $current;
}
$path = 'level1.level2.level3';
// will be converted to get the value 'my data' from the array below
$data['level1']['level2']['level3'] = 'my data';
var_dump( retrieve( $data, $path ) );
It is a tricky one this, here is the most efficient way I can think of:
function get_value_from_array ($array, $path, $pathSep = '.') {
foreach (explode($pathSep, $path) as $pathPart) {
if (isset($array[$pathPart])) {
$array = $array[$pathPart];
} else {
return FALSE;
}
}
return $array;
}
Returns the value, or FALSE on failure.
Try
$index = "data";
echo $$index['level1']['level2']['level3'];
instead, because $index should be only variable name
Something like this:
eval('$data[\''.implode("']['",explode('.',$path))."'] = 'my data';");
...but don't ever, ever tell anyone I told you to do this.
You can use eval function like so:
$data['level1']['level2']['level3'] = 'my data';
eval("\$index = \$data['level1']['level2']['level3'];");
echo $index;
One of my colleges seem to have an 'undefined index' error on a code I wrote
This code of mine looks like this:
if ( is_array ($arr['key']))
My intention was to check whether $arr has a key named 'key', and if the value of that key is array itself. Should I do instead: if( isset($arr['key']) && is_array ($arr['key'])) ?
Maybe the following is equivavlent:
Let's assume $var is not set. Then, will is_array($var) cause an error or will it just return false?
Thank you
Yes, use isset, then is_array.
if(isset($arr['key']) && is_array($arr['key'])) {
// ...
}
Because PHP uses short-circuit logic evaluation, it will stop before it gets to is_array(), so you'll never get an error.
Try:
is_array($arr) && array_key_exists('key', $arr)
check if it exists first, then if its an array. Otherwise you will still get the same error.
if ( isset($arr['key'])) {
if (is_array ($arr['key']) {
}
}
Maybe you can consider a generic get() function for safe-retrieving data from arrays:
/*
Get with safety
#author: boctulus
#param array
#param index1
#param index2
..
*/
function get(){
$numargs = func_num_args();
$arg_list = func_get_args();
$v = $arg_list[0];
for ($i = 1; $i < $numargs; $i++)
{
if (isset($v[$arg_list[$i]]))
$v = $v[$arg_list[$i]];
else
return null;
}
return $v;
}
Use:
$arr = [];
var_dump( get($arr,'a','b') ); // NULL
$arr['a']['b'] = 'ab';
var_dump( get($arr,'a','b') ); // 'ab'
My goal is to echo the argument passed to a function. For example, how can this be done?
$contact_name = 'foo';
function do_something($some_argument){
// echo 'contact_name' .... How???
}
do_something($contact_name);
You can't. If you want to do that, you need to pass the names as well, e.g:
$contact_name = 'foo';
$contact_phone = '555-1234';
function do_something($args = array()) {
foreach ($args as $name => $value) {
echo "$name: $value<br />";
}
}
do_something(compact('contact_name', 'contact_phone'));
Straight off the PHP.net variables page:
<?php
function vname(&$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;
}
?>
Not possible.
Variables are just means to address values or areas in the memory. You cannot get the variable name that’s value has been passed to a function.
Disclaimer: this will oonly work if you pass a variable to the function, not a value, and it only works when your not in a function or a class. So only the GLOBAL scope works :)
Good funct($var)
Bad funct(1)
You can do it actually contrary to popular believe ^_^. but it involves a few lookup tricks with the $GLOBALS variable.
you do it like so:
$variable_name = "some value, better if its unique";
function funct($var) {
foreach ($GLOBALS as $name => $value) {
if ($value == $var) {
echo $name; // will echo variable_name
break;
}
}
}
this method is not fool proof tho. Because if two variables have the same value, the function will get the name of the first one it finds. Not the one you want :P
Its best to make the variable value unique before hand if you want accuracy on variable names
Another method would be to use reference to be accurate like so
$variable_name = 123;
function funct(&$var) {
$old = $var;
$var = $checksum = md5(time()); // give it unique value
foreach ($GLOBALS as $name => $value) {
if ($value == $var) {
echo $name; // will echo variable_name
$var = $old; // reassign old value
break;
}
}
}
so it is entirely possible :)
Based on PTBNL's (most definately correct) answer i came up with a more readable (at least i think so) approach:
/**
* returns the name of the variable posted as the first parameter.
* If not called from global scope, pass in get_defined_vars() as the second parameter
*
* behind the scenes:
*
* this function only works because we are passing the first argument by reference.
* 1. we store the old value in a known variable
* 2. we overwrite the argument with a known randomized hash value
* 3. we loop through the scope's symbol table until we find the known value
* 4. we restore the arguments original value and
* 5. we return the name of the symbol we found in the table
*/
function variable_name( & $var, array $scope = null )
{
if ( $scope == null )
{
$scope = $GLOBALS;
}
$__variable_name_original_value = $var;
$__variable_name_temporary_value = md5( number_format( microtime( true ), 10, '', '' ).rand() );
$var = $__variable_name_temporary_value;
foreach( $scope as $variable => $value )
{
if ( $value == $__variable_name_temporary_value && $variable != '__variable_name_original_value' )
{
$var = $__variable_name_original_value;
return $variable;
}
}
return null;
}
// prove that it works:
$test = 1;
$hello = 1;
$world = 2;
$foo = 100;
$bar = 10;
$awesome = 1;
function test_from_local_scope()
{
$local_test = 1;
$local_hello = 1;
$local_world = 2;
$local_foo = 100;
$local_bar = 10;
$local_awesome = 1;
return variable_name( $local_awesome, get_defined_vars() );
}
printf( "%s\n", variable_name( $awesome, get_defined_vars() ) ); // will echo 'awesome'
printf( "%s\n", test_from_local_scope() ); // will also echo awesome;
Sander has the right answer, but here is the exact thing I was looking for:
$contact_name = 'foo';
function do_something($args = array(), $another_arg) {
foreach ($args as $name => $value) {
echo $name;
echo '<br>'.$another_arg;
}
}
do_something(compact(contact_name),'bar');
class Someone{
protected $name='';
public function __construct($name){
$this->name=$name;
}
public function doSomthing($arg){
echo "My name is: {$this->name} and I do {$arg}";
}
}
//in main
$Me=new Someone('Itay Moav');
$Me->doSomething('test');