0

Is it possible to use a for loop where $i is part of the variable name? I'm trying to get this for loop to list the fruits:

$item1name = "apple";
$item2name = "orange";
$item3name = "banana";

for($i=0, $i<2, $i++) {
  echo = "<li>$item?????</li>";
}

// should result in:
// <li>apple</li><li>orange</li><li>banana</li>

I realize I can put the fruits in an $itemname array and easily echo $itemname[$i], but that isn't what I'm asking. Is it possible to do this when $i is part of the variable name?

3
  • 2
    Just use an array instead. Commented Mar 30, 2014 at 20:07
  • Of course, I already noted that I could do that, but it's not what I'm asking. Thanks @Amal. Commented Mar 30, 2014 at 20:08
  • Thanks @BlackPearl. Would you care to elaborate? Commented Mar 30, 2014 at 20:09

1 Answer 1

3

It is possible with the use of variable variables:

for($i=1; $i<=3; $i++) {
    echo "<li>" . ${'item'.$i.'name'} . "</li>";
}

Note that your original code wasn't syntactically correct. I've fixed it. Also note how $i value changed. Your variable numbers are from 1 to 3, not 0 to 1.

But I don't see why you'd want this. Simply use an array instead.

Demo

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

2 Comments

Thanks Amal. That's what I was looking for. I'm working with existing data columns named similar to $itemXname. In my case, they're simple enough to load into an array like "array($item1name,$item2name,$item3name)", but your answer is helpful in cases where that cannot be done programmatically or where the numbers in the column names would not correspond to their indexed value. Thanks again!
@JoshRencher: No problem. Glad to have been of help!

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.