Convert a String to Variable

4 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!"

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


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.

I'm having trouble understanding exactly what it is you're trying to do, but here's a generic suggestion for what you might be able to do...

$checked[1] = $row['rmc_induction_softskill']
$checked[2] = $row['rmc_induction_neo']

for ($i=0;$i<sizeof($checked);$i++) {
    echo $checked[$i];

Don't know if this is what you're looking for, so let me know if you need something more specific and add some extra information so I know a bit better what you're trying to do.

Need to print variable inside a variable php mysql

You can't use checked{$i} to simulate checked1 or checked2 or ... What you have to do is to put/push everything into an array with key value pair and then recover them based on the index of the list. I believe your MySQL read returns an array of key value pair so you can loop through that, but if you want to choose the specific fields, then you can create an array in PHP and push the items in it. Let me give you an example:

// insert into the checked array. Insert all those fields/rows that you want 
$checked = array($row['rmc_induction_softskill'], $row['rmc_induction_neo'], $row['rmc_induction_itil']);

for ($i=1; $i<=count($checked); $i++){
$checkedTemp = checked[$i];
echo $checkedTemp;
<td align="center" bgcolor="#E6E6FA">  <input type="checkbox" id="<?php echo   $i.$rows['emp_id']; ?>" name="Emails[]" value="<?php echo $i.";".$concatenated_string; ?>" <?php if ($checkedTemp == 1) echo "checked" ; ?>  onclick="check(<?php echo $i.$rows['emp_id']; ?>);"  /></td>

So that is a way of doing it. Based on the order you insert into the array you can take it out too.

function findInDepth($keys, $array){
    $key = array_shift($keys);
        return FALSE;
        return findInDepth($keys, $array[$key]);
    return $array[$key];
$key = "user[username]";
$keys = preg_split("/(\[|\])/", $key);
echo findInDepth($keys, $request);

This function solves my problem. It first splits the string (aka the input name) into an array of keys and then recessively searches in depth the array by keys until it finds a value which is not an array and returns FALSE otherwise.

How to convert string (name of a variable) to a variable in PHP?

how about this:

$a = 'myvariable["subitem"]';
echo $$a;

Above is called variable variables