Gilean
Gilean

Reputation: 14748

Convert a String to Variable

I've got a multidimensional associative array which includes an elements like

$data["status"]
$data["response"]["url"]
$data["entry"]["0"]["text"]

I've got a strings like:

$string = 'data["status"]';
$string = 'data["response"]["url"]';
$string = 'data["entry"]["0"]["text"]';

How can I convert the strings into a variable to access the proper array element? This method will need to work across any array at any of the dimensions.

Upvotes: 20

Views: 89861

Answers (10)

Abdul Samad
Abdul Samad

Reputation: 78

You can also use curly braces (complex variable notation) to do some tricks:

$h = 'Happy';
$n = 'New';
$y = 'Year';
$wish = ${$h.$n.$y};
echo $wish;

Upvotes: 1

Nikita Kalitin
Nikita Kalitin

Reputation: 183

Perhaps this option is also suitable:

$data["entry"]["0"]["text"];
$string = 'data["entry"]["0"]["text"]';

function getIn($arr, $params)
{
    if(!is_array($arr)) {
        return null;
    }
    if (array_key_exists($params[0], $arr) && count($params) > 1) {
        $bf = $params[0];
        array_shift($params);
        return getIn($arr[$bf], $params);
    } elseif (array_key_exists($params[0], $arr) && count($params) == 1) {

        return $arr[$params[0]];
    } else {
        return null;
}
}

preg_match_all('/(?:(\w{1,}|\d))/', $string, $arr_matches, PREG_PATTERN_ORDER);

array_shift($arr_matches[0]);
print_r(getIn($data, $arr_matches[0]));

P.s. it's work for me.

Upvotes: 0

Dima Storozhuk
Dima Storozhuk

Reputation: 33

There are native PHP function for this: use http://php.net/manual/ru/function.parse-str.php (parse_str()).

don't forget to clean up the string from '"' before parsing.

Upvotes: 0

gus
gus

Reputation: 1

You can pass by reference with the operator &. So in your example you'll have something like this

$string = &$data["status"];
$string = &$data["response"]["url"];
$string = &$data["entry"]["0"]["text"];

Otherwise you need to do something like this:

$titular = array();
for ($r = 1; $r < $rooms + 1; $r ++)
{
    $title = "titular_title_$r";
    $firstName = "titular_firstName_$r";
    $lastName = "titular_lastName_$r";
    $phone = "titular_phone_$r";
    $email = "titular_email_$r";
    $bedType = "bedType_$r";
    $smoker = "smoker_$r";

    $titular[] = array(
        "title" => $$title,
        "first_name" => $$firstName,
        "last_name" => $$lastName,
        "phone" => $$phone,
        "email" => $$email,
        "bedType" => $$bedType,
        "smoker" => $$smoker
    );
}

Upvotes: 0

MattBelanger
MattBelanger

Reputation: 5350

You would access them like:

print $$string;

Upvotes: 0

Brandon S
Brandon S

Reputation: 61

This can be done in a much simpler way. All you have to do is think about what function PHP provides that creates variables.

$string = 'myvariable';
extract(array($string => $string));
echo $myvariable;

done!

Upvotes: 6

user763694
user763694

Reputation: 188

I was struggling with that as well, I had this :

$user  =  array('a'=>'alber', 'b'=>'brad'...);

$array_name = 'user';

and I was wondering how to get into albert.

at first I tried

$value_for_a = $$array_name['a']; // this dosen't work 

then

eval('return $'.$array_name['a'].';'); // this dosen't work, maybe the hoster block eval which is very common

then finally I tried the stupid thing:

$array_temp=$$array_name;
$value_for_a = $array_temp['a'];

and this just worked Perfect! wisdom, do it simple do it stupid.

I hope this answers your question

Upvotes: 0

Gilean
Gilean

Reputation: 14748

Found this on the Variable variables page:

function VariableArray($data, $string) { 
    preg_match_all('/\[([^\]]*)\]/', $string, $arr_matches, PREG_PATTERN_ORDER); 

    $return = $arr; 
    foreach($arr_matches[1] as $dimension) { $return = $return[$dimension]; }

    return $return; 
} 

Upvotes: 0

Allain Lalonde
Allain Lalonde

Reputation: 93348

Quick and dirty:

echo eval('return $'. $string . ';');

Of course the input string would need to be be sanitized first.

If you don't like quick and dirty... then this will work too and it doesn't require eval which makes even me cringe.

It does, however, make assumptions about the string format:

<?php
$data['response'] = array(
    'url' => 'http://www.testing.com'
);

function extract_data($string) {
    global $data;

    $found_matches = preg_match_all('/\[\"([a-z]+)\"\]/', $string, $matches);
    if (!$found_matches) {
            return null;
    }

    $current_data = $data;
    foreach ($matches[1] as $name) {
            if (key_exists($name, $current_data)) {
                    $current_data = $current_data[$name];
            } else {
                    return null;
            }
    }

    return $current_data;
} 

echo extract_data('data["response"]["url"]');
?>

Upvotes: 25

clawr
clawr

Reputation: 7895

PHP's variable variables will help you out here. You can use them by prefixing the variable with another dollar sign:

$foo = "Hello, world!";
$bar = "foo";
echo $$bar; // outputs "Hello, world!"

Upvotes: 64

Related Questions