1

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!

5
  • 7
    That's what arrays are for, is there a reason you can't use an array? Commented Jul 11, 2012 at 21:26
  • i have tryed $id[1]= "example" . $i; but its not working. i think the syntax is wrong Commented Jul 11, 2012 at 21:28
  • It is possible using variable variables, but not recommended: ideone.com/gjvIX. Commented Jul 11, 2012 at 21:29
  • Just initialize the array before your loop and use $id[$i] = "example" . $i in the loop Commented Jul 11, 2012 at 21:30
  • the syntax would be $id[$i] instead of $id[1]. What you tried would be putting each string in position 1 of the array Commented Jul 11, 2012 at 21:31

5 Answers 5

6

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;
}
Sign up to request clarification or add additional context in comments.

4 Comments

what should be inside the []?
Nothing. $id[] means append to the end of array $id.
Note that array indices start from 0; if you REALLY want the indices to start from 1, you can use $id[$i] in this particular case instead.
I know about arrays i just aint knew that [] means the end of the array. thank you! it works.
0

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;
}

Comments

0

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;
}

Comments

0

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;
}

Comments

0
$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?

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.