ILS
ILS

Reputation: 143

PHP dynamical variable declaration

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.

Upvotes: 2

Views: 54

Answers (2)

alexander.polomodov
alexander.polomodov

Reputation: 5534

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:)

Upvotes: 1

C.Liddell
C.Liddell

Reputation: 1082

Try this:

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

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

Upvotes: 2

Related Questions