Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP dynamically accessing variable value

Tags:

variables

php

I want to dynamically access value of variable, let's say I have this array:

$aData = array(
  'test' => 123
);

Standard approach to print the test key value would be:

print $aData['test'];

However, if I have to work with string representation of variable (for dynamic purposes)

$sItem = '$aData[\'test\']';

how can I achieve to print aData key named test? Neither of examples provided below works

print $$sItem;
print eval($sItem);

What would be the solution?

like image 978
nabizan Avatar asked Dec 02 '11 12:12

nabizan


People also ask

What is a dynamic variable in PHP?

The dynamic variable is a user-defined php code that must return a string value. To create a new dynamic variable, follow these steps: Go to Catalog → Advanced Product Feeds → Dynamic Variables.

What does a $$$ mean in PHP?

PHP $ and $$ Variables. The $var (single dollar) is a normal variable with the name var that stores any value like string, integer, float, etc. The $$var (double dollar) is a reference variable that stores the value of the $variable inside it.

How can get input field value in PHP variable?

Use PHP's $_POST or $_GET superglobals to retrieve the value of the input tag via the name of the HTML tag.


2 Answers

Your eval example is lacking the return value:

print eval("return $sItem;");

should do it:

$aData['test'] = 'foo';

$sItem = '$aData[\'test\']';

print eval("return $sItem;"); # foo

But it's not recommended to use eval normally. You can go into hell's kitchen with it because eval is evil.

Instead just parse the string and return the value:

$aData['test'] = 'foo';

$sItem = '$aData[\'test\']';

$r = sscanf($sItem, '$%[a-zA-Z][\'%[a-zA-Z]\']', $vName, $vKey);
if ($r === 2)
{
    $result = ${$vName}[$vKey];
}
else
{
    $result = NULL;
}

print $result; # foo

This can be done with some other form of regular expression as well.

As your syntax is very close to PHP an actually a subset of it, there is some alternative you can do if you want to validate the input before using eval. The method is to check against PHP tokens and only allow a subset. This does not validate the string (e.g. syntax and if a variable is actually set) but makes it more strict:

function validate_tokens($str, array $valid)
{
    $vchk = array_flip($valid);
    $tokens = token_get_all(sprintf('<?php %s', $str));
    array_shift($tokens);
    foreach($tokens as $token)
        if (!isset($vchk[$token])) return false;
    return true;
}

You just give an array of valid tokens to that function. Those are the PHP tokens, in your case those are:

T_LNUMBER (305) (probably)
T_VARIABLE (309)
T_CONSTANT_ENCAPSED_STRING (315)

You then just can use it and it works with more complicated keys as well:

$aData['test'] = 'foo';
$aData['te\\\'[]st']['more'] = 'bar';

$sItem = '$aData[\'test\']';
$vValue = NULL;
if (validate_tokens($sItem, array(309, 315, '[', ']')))
{
    $vValue = eval("return $sItem;");
}

I used this in another answer of the question reliably convert string containing PHP array info to array.

like image 144
hakre Avatar answered Sep 24 '22 17:09

hakre


No eval necessary if you have (or can get) the array name and key into separate variables:

$aData = array(
  'test' => 123
);

$arrayname = 'aData';
$keyname = 'test';

print ${$arrayname}[$keyname]; // 123
like image 24
Boann Avatar answered Sep 22 '22 17:09

Boann