Jump to content

Convert Variable name into string


slpwkr

Recommended Posts

I'm bit confused with you saying without the $ because aint just just

echo "variablename";

above will read as: variablename

or did you mean actualy echo $variablename e.g.

echo '$variablename';

above will read as: $variablename


Nott 100% on what you mean?
its like this:

[code]
$variablename= 'whatever';

echo $variablename;

# output: Whatever

echo '$variablename';

# output: $variablename

echo substr('$variablename',1);

# output: variablename <--- this is the one i need
[/code]

what I need is to do is... Use the $variablename and print variablename just like the 3rd example but not using substr. Is there any other way?

Thanx, but I don't think what im trying to do is possible. Its something like this

[code]

function myfunc ($variable) {
global $array;

$array[$variable]=$variable;
}


$var1='my 1st string';
$var2='my 2nd string';

myfunct ($var1);
myfunct ($var2);

print_r($array);

#I want an output something like this: ('var1'=>'this is my 1st string', 'var2'=>'this is my 2nd string')

[/code]
Wouldn't this work then?

[code]function myfunc ($variable) {
global $array;
$variable2=str_replace('$','','$variable);
$array["$variable2"]=$variable;
}


$var1='my 1st string';
$var2='my 2nd string';

myfunct ($var1);
myfunct ($var2);

print_r($array);

#I want an output something like this: ('var1'=>'this is my 1st string', 'var2'=>'this is my 2nd string')
[/code]


Not sure if that's what your looking for..
Try this code. It takes advantage of the superglobal array $GLOBALS. One thing you should be aware of is that if you have more than one variable with the same value, only the first one will be found.

[code]<?php
function myfunc($var)
{
   $defk = 'no_var';
   foreach($GLOBALS as $k => $v)
    if (!is_array($k) && $v == $var) return($k);
   return($defk);
}

        $test1 = "This is a test";
    $yat   = 'This is yet another test';
    $yat2 = 'This is yet another test';
    $new_array = array();
    $new_array[myfunc($test1)] = $test1;
    $new_array[myfunc($yat)] = $yat;
    $new_array[myfunc($yat2)] = $yat2;
    $tmp = array();
    foreach ($new_array as $k => $v)
        $tmp[] = "'" . $k . "' => '" . $v . "'";
    echo '<pre>(' . implode(', ',$tmp) . ')</pre>';
?>[/code]

Ken

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.