Search code examples
phparraysvariable-variables

Looping variable variables, illegal string offset


I keep getting

Warning: Illegal string offset 'type' in ... on line ...

I've tried following the answers here Illegal string offset Warning PHP

by doing something like

if(isset($_POST['type_'.$i]))
     $$T['type'] = $_POST['type_'.$i];

but it still gives errors, I think it might have something to do with variable variables (it's the first time I am using them. Below is my code:

for($i = 1; $i <= 15; $i++){
    $T = 'T'.$i;

    $$T['type'] = $_POST['type_'.$i];
    $$T['hidden'] = $_POST['hidden_'.$i];
    $$T['require'] = $_POST['require_'.$i];
    if(isset($_POST['question_'.$i.'_list']))
        $$T['list'] = $_POST['quesiton_'.$i.'_list'];
}

I won't like to create arrays T1, T2 ... T15, with the following values ['type'], ['hidden'], ['require'], ['list'].


Solution

  • The problem is one of precedence. $T['type'] is resolved first, and then used as the variable name for $___.

    Since $T is a string, ['type'] is an invalid offset to get.

    You could do this:

    ${$T}['type']
    

    ... I think. I wouldn't really know, because stuff like this is what arrays were kinda made for ;)

    $T = array();
    for( $i = 1; $i <= 15; $i++) {
        $row = array(
            "type" => $_POST['type_'.$i],
            "hidden" => $_POST['hidden_'.$i],
            "require" => $_POST['require_'.$i]
        );
        if( isset($_POST['question_'.$i.'_list'])) {
            $row['question_'.$i.'_list'] = $_POST['question_'.$i.'_list'];
        }
        $T[] = $row;
    }