-1

I tried to do somthing like that:

$cat1 = array('hello', 'everyone');
$cat = array('bye', 'everyone');

for($index = 0; $index < 2; $index++) {
echo $cat$index[1];
}

It doesn't work of course. What do I need to change here?

3
  • 1
    Why are you not using nested arrays? Commented Dec 1, 2010 at 17:40
  • Please go back to your questions and mark the best answer. Commented Dec 1, 2010 at 17:54
  • 1
    This is one of those examples where one should suggest a better, alternative solution instead of a direct answer. Commented Dec 1, 2010 at 18:11

5 Answers 5

1

You should use nested arrays, but this can be done.

$cat1 = array('hello', 'everyone');
$cat2 = array('bye', 'everyone');

for($i = 1; $i <= 2; $i++) {
    echo ${'cat' . $i}[1];
}

Reference: http://php.net/language.variables.variable

This would be much better though:

$cats = array(
    array('hello', 'everyone'),
    array('bye', 'everyone')
);
foreach ($cats as $cat) {
    echo $cat[1];
}
Sign up to request clarification or add additional context in comments.

Comments

1

Is this what you intended?

$cat0 = array('hello', 'everyone');
$cat1 = array('bye', 'everyone');

for($index = 0; $index < 2; $index++) {
    $varname = 'cat'.$index;
    echo $varname[0].' '.$varname[1];
}

Comments

1

If you insist on doing it this way...

echo ${'cat' . $index}[1];

Comments

0

To echo elements inside arrays, you need to be using

echo $cat[$index]

with your example.

I'm not sure what the $index[1] is supposed to be doing? Maybe I have misunderstood your question.

Comments

0

You can't reference $index like that, it isn't an array.

echo $cat[$index];

is what you want to do.

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.