Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a String to Variable

Tags:

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.

like image 580
Gilean Avatar asked Jan 11 '09 17:01

Gilean


People also ask

Can you convert a string to a variable in JavaScript?

Well, it is possible, and here in this simple tutorial, I am going to show you how to convert any string into a variable in JavaScript. To do this task, we will use the JavaScript eval() function. Well, this is the function that will play the main role to create variable name from our string.

Can you put a string in a variable?

In JavaScript, we can assign strings to a variable and use concatenation to combine the variable to another string. To concatenate a string, you add a plus sign+ between the strings or string variables you want to connect.

Can you use a string to name a variable?

We can assign character string to variable name by using assign() function. We simply have to pass the name of the variable and the value to the function.

How do you save a string as a variable in Python?

Declaring strings as variables can make it easier for us to work with strings throughout our Python programs. To store a string inside a variable, we need to assign a variable to a string. In this case let's declare my_str as our variable: my_str = "Sammy likes declaring strings."


2 Answers

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!"
like image 131
clawr Avatar answered Sep 29 '22 19:09

clawr


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"]');
?>
like image 33
Allain Lalonde Avatar answered Sep 29 '22 18:09

Allain Lalonde