Home > Software engineering >  Substitute a PHP variable name according to its value
Substitute a PHP variable name according to its value

Time:09-17

I have the following variables set:

$type = 'cd';
$type_cd = 'Compact Disc';

$type's value is stored in MySQL database and could be whatever.

But in some specific place of the code I need to echo $type_cd; instead of echo $type; in case $type = 'cd';.

I want to avoid constructions like if($type = 'cd') {echo $type_cd;}, using the minimum possible code.

Is it possible with PHP to create something like $newvar = $ prefix oldvar_value?

CodePudding user response:

Use an array instead of multiple variables. You can define these in some class or in some config so you can reuse them where ever:

$availableTypes = [
    'cd'  => 'Compact Disc',
    'foo' => 'bar', 
    ...
];

Then when you get the type from the database, all you need to do is:

$type = 'cd'; // Fetched from your database

echo $availableTypes[$type];

CodePudding user response:

Does this help?

$type = 'cd';
$$type = 'Compact Disc';
echo $cd;

It will echo "Compact Disc". I do not see it as best practice... You can find the documentation here

CodePudding user response:

Yes, you can:

$a = 'ab';
$ab = 2
echo $$a; // 2

For your example:

$type = 'cd';
$type_cd = 'Compact Disc';

// a variable that holds the type
$temp_type = $is_cd ? 'type' : 'type_cd';

echo $$temp_type;

  • Related