Access a variable using a counter as part of the variable name

前端 未结 5 1892
清歌不尽
清歌不尽 2021-01-29 08:52

I tried to do somthing like that:

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

for($index = 0; $index < 2; $index++) {
echo $         


        
相关标签:
5条回答
  • 2021-01-29 08:58

    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];
    }
    
    0 讨论(0)
  • 2021-01-29 08:58

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

    echo $cat[$index];
    

    is what you want to do.

    0 讨论(0)
  • 2021-01-29 08:59

    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.

    0 讨论(0)
  • 2021-01-29 09:04

    If you insist on doing it this way...

    echo ${'cat' . $index}[1];
    
    0 讨论(0)
  • 2021-01-29 09:05

    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];
    }
    
    0 讨论(0)
提交回复
热议问题