2

I'm dynamically declaring variables using the following code:

$fields = array('name1', 'name2');

foreach($fields as $field) {
    $$field = false;
}

The problem is there are variable names that overlap, since I'm using more than one array.

The question is: How could I append a letter to the variable name using the previous method?

For example if we were to append the letter F to the previous example, then we'd get $Fname1, $Fname2.

I tried to do $F$field but that doen't work, I also tried to set $field = "F"+$field inside the loop but didn't work either.

5
  • 5
    If you're running ino problems with this, then perhaps PHP telling you that it isn't the best way to o whatever it is you're trying to do.... perhaps explain what you're trying to achieve, and we may be able to show you a better alternative approach.... perhaps even something as simple as $fieldSet = array_fill_keys($fields, false);.... but if you have duplicate variable names, then you're certainly approaching this the wrong way Commented Mar 10, 2016 at 21:30
  • 1
    I agree with Mark - IMO there aren't many situations where you need to use variable variables. Often just using an associative array will do the trick but let you circumvent problems like this from happening. Commented Mar 10, 2016 at 21:31
  • The array is used to set variable names, build form fields, and sql queries dynamically. The only problem so far is in case of overlapping field names (when using more than one table) Commented Mar 10, 2016 at 21:34
  • 2
    To concatenate strings you use a period ".", not a plus symbol "+". Commented Mar 10, 2016 at 21:37
  • @C.Liddell I can't believe I overlooked that... Thanks. Commented Mar 10, 2016 at 21:43

2 Answers 2

2

Try this:

$fields = array('name1', 'name2');

foreach($fields as $field) {
    $field = "F" . $field;
    $$field = false;
}
Sign up to request clarification or add additional context in comments.

Comments

1

Try to use this:

$fields = array('name1', 'name2', 'name1', 'name2', 'name2');

foreach($fields as $field) {
    while(!is_null($$field)) {
        $field = "F".$field;
    }
    $$field = false;
    var_dump($field);
}

Output:

string(5) "name1"
string(5) "name2"
string(6) "Fname1"
string(6) "Fname2"
string(7) "FFname2"

So you will append F letter for each overlapped variables:)

Comments

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.