November 28, 2011

How to concatenate a string and a variable into a constant name?

Question by rajzana

I have a constant like define(“EMPLOYEE_NAME_ID”,”employee”); and a variable $code = EMPLOYEE;

now i want to print like below

<?php echo $code.NAME_ID; ?>

But this prints only “EMPLOYEE_NAME_ID” and i want to print “employee”. Then how to print this. The all over means is that i want to retriew variables from lang file.

Answer by ajreal

A unquote string in PHP will be parsed as constant,
and if the constant is undefined,
it will treat as the string (instead of a variable)

If you dealing with constant, you can make use of constant function :-

echo constant("{$code}_NAME_ID");

However, use of this function will return warning message if the constant is not defined.
There are other option like parse_ini_file you can take a look,
this is ideal for handling large amount of setting / configuration

Answer by Starx

Better way would be to use constant function

echo constant($code."NAME_ID");

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+


Please fill the form - I will response as fast as I can!