EtayRock
EtayRock

Reputation: 113

php variable after a variable in for loop

I need a way to do this

for($i=1;$i<=10;$i++){
$id$i = "example" . $i;
}

notice the second line has $id$i so for the first loop $id1 will equal example1 in the second loop $id2 will equal example2 and so on... Thank you very much!

Upvotes: 1

Views: 86

Answers (5)

Federkun
Federkun

Reputation: 36934

$var = array();
for($i=1; $i<=10; $i++) {
$var['id' . $i] = 'example' . $i;
}
extract($var, EXTR_SKIP);
unset($var);

but why not use a simple array?

Upvotes: 0

Brian J
Brian J

Reputation: 694

You could create an array of size $i with a name of $id, and insert each element into a different index.

for($i=1;$i<=10;$i++){
    $id[$i] = "example" . $i;
}

Upvotes: 0

Andrew
Andrew

Reputation: 2154

It would be much better to use an array, but you could do this:

for($i=1; $i<=10; $i++){
    $var ="id$i";
    $$var = "example" . $i;
}

Here's what I would recommend doing instead:

$ids = array;
for($i = 1; $i <= 10; $i++) {
    $ids[$i] = "example" . $i;
}

Upvotes: 0

Stefan Fandler
Stefan Fandler

Reputation: 1141

You can convert a string into a variable (the name of the variable), if you put another $ in front of it:

$str = "number";
$number = 5;
$$str = 8;
echo $number;  // will output 8

So in your example, you could do it like that:

for($i = 1; $i <= 10; $i++) {
    $str_var = "id".$i;
    $$str_var = "example".$i;
}

Upvotes: 0

Palladium
Palladium

Reputation: 3763

You can use variable variable names to do this; however, it's probably much more convenient if you just used an array:

for($i = 1, $i <= 10, $i++) {
    $id[] = "example" . $i;
}

Upvotes: 6

Related Questions