0

I have a badly designed Database that I have to deal with. In order to have a smaller code footprint, I need to use dynamic variable naming in PHP. However, the names of each variable vary greatly. Here's a sample of my code:

<?php

    $test = (object)[
        'variable_1_text'   => 'ONE',
        'variablevv_1_another_one'   => 'Two',
        'variablett_1_blah'   => 'III',
        'variablex_1_text_lala'   => 'Four',
        'variable_2_text'   => 'ONE',
        'variablevv_2_another_one'   => 'Two',
        'variablett_2_blah'   => 'III',
        'variablex_2_text_lala'   => 'Four',
        'variable_3_text'   => 'ONE',
        'variablevv_3_another_one'   => 'Two',
        'variablett_3_blah'   => 'III',
        'variablex_3_text_lala'   => 'Four',
        'variable_4_text'   => 'ONE',
        'variablevv_4_another_one'   => 'Two',
        'variablett_4_blah'   => 'III',
        'variablex_4_text_lala'   => 'Four',
    ];

    //this doesn't work
    foreach (array(1,2,3,4) as $temp_val) {
        echo $test->variable_{$temp_val}_text . "<br />";
        echo $test->variablevv_{$temp_val}_another_one . "<br />";
        echo $test->variablett_{$temp_val}_blah . "<br />";
        echo $test->variablex_{$temp_val}_text_lala . "<br />";
    }

?>

There's a lot of these variables. I just need how to dynamically make those 1, 2, 3, and 4 in between the names of the variable names. Is this even possible?

2
  • use curly braces to access such object properties Commented May 15, 2018 at 1:51
  • I'm not sure what you meant. I tried using curly braces in my sample code above but that doesn't work. Maybe I'm doing it wrong? Commented May 15, 2018 at 5:45

1 Answer 1

1

You can try this: $test->{'variable_'.$temp_val.'_text'};

Sign up to request clarification or add additional context in comments.

1 Comment

Hi FoxVSky, but this would let me change all of the variable names. Like the word 'variable_' and '_text' varies from all of the variables. I only need to dynamically concatenate the 1, 2, 3, and 4 in the existing variable names.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.