1

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'].

Community
  • 1
  • 1
Arian Faurtosh
  • 17,987
  • 21
  • 77
  • 115
  • 1
    Try adding `$$T = array();` before trying to assign any values to it. – Styphon Jun 10 '14 at 22:16
  • so you want each of your `T` variables to be arrays? What if you set them to be before setting the values inside them? `$$T = array();` – didierc Jun 10 '14 at 22:16
  • @Styphon adding `$$T = array();` didn't work – Arian Faurtosh Jun 10 '14 at 22:17
  • 1
    Either the variable `$T` is not an array and you are trying to access it like it is or you need to wrap `$T['type']` in curly braces because the `$$T` assignment is happening before the array lookup. Try `${$T['type']}`. Curly braces in assignment are like parenthesis in expressions. `$$T` is likely doing a string conversion of the array `$T` making a variable called `$Array` and then looking up a key of `['type']` on the string. – Jonathan Kuhn Jun 10 '14 at 22:17

2 Answers2

3

How's that?

for($i = 1; $i <= 15; $i++){
    $T = 'T'.$i;
    $$T = array(
      'type' => $_POST['type_'.$i], 
      'hidden' => $_POST['hidden_'.$i],
      'require' => $_POST['require_'.$i]);

    if(isset($_POST['question_'.$i.'_list']))
        ${$T}['list'] = $_POST['question_'.$i.'_list'];
}
didierc
  • 14,572
  • 3
  • 32
  • 52
2

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;
}
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592