3

Is it possible to convert a string variable to upper case. The variable itself and not the content of the variable.

For example :-

  $name = "Jam"
  $data = function ?($name);

Such that $data contains "NAME". $name is passed as a variable in a function and can be $name or $game or anything. The fact of the matter is that I am trying to capitalize the variable name. Is there anyway that can be achieved in php.

  strtoupper($name)
  -->Output : JAM

That's not what I want I need the variable to be capitalized. I would appreciate any sort of assistance.

  • Why would you want to do that in the first place? – Matt Feb 14 '16 at 02:48
  • @Matt I had fields coming from the database which mapped onto my properties, so I wanted to lower the case... –  Feb 14 '16 at 17:04

4 Answers4

1

you can use the php strtoupper() if you want all of you string to be on the uppercase but if you want only the first letter of the string to uppercase ucfirst()

poliam
  • 67
  • 1
  • 1
  • 6
  • 1
    OP wants to convert the variable name itself and not variable content –  Jul 04 '17 at 23:09
0

You can use PHP strtoupper() function:

CODE

<?php

$name = 'Jam';

    echo strtoupper(print_var_name($name));

function print_var_name($var) {
    foreach($GLOBALS as $var_name => $value) {
        if ($value === $var) {
            return $var_name;
        }
    }

    return false;
}

?>

OUTPUT

NAME

Adapted from How to get a variable name as a string in PHP?.

Community
  • 1
  • 1
Panda
  • 6,955
  • 6
  • 40
  • 55
0

"... $name is passed as a variable in a function ..." then it changes to the variable name in the function definition - original variable name doesn't matter at that point. So your function never know the variable's name. * Obviously there is a way for this. Shown in EDIT *

However, if you want to create a variable as an uppercase version of another variable - which I have no clue what to do with this - then this will do that for you.

$name = "Jam";
${strtoupper("name")} = $name;
print $NAME;

* EDIT *: I had no idea about this and very strange and converted from the link I posted in my comment and I have still no idea why it could be even used but:

function magicfunc($var)
{
   foreach($GLOBALS as $k => $v) { 
       if (!is_array($k) && $v == $var) return(strtoupper($k));
   }
}

$name = "1234";

${magicfunc($name)} = $name;

// Yes, we have this variable
print $NAME;
smozgur
  • 1,772
  • 1
  • 15
  • 23
  • @Umar Aftab : interesting and I had no idea but please check the last post here: http://forums.phpfreaks.com/topic/3815-convert-variable-name-into-string/ – smozgur Feb 14 '16 at 03:02
  • It actually gave me output 'Jam' after I tried it ;) – Panda Feb 14 '16 at 03:09
-1
<?php

$name = 'Jam';
$vars = get_defined_vars();

foreach ($vars as $key => $var) {
    if ($var == 'Jam') {
        $data = strtoupper($key);
    }
}

echo $data;
Jeroen Flamman
  • 965
  • 6
  • 10