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

4
  • 1
    Try adding $$T = array(); before trying to assign any values to it. Commented Jun 10, 2014 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(); Commented Jun 10, 2014 at 22:16
  • @Styphon adding $$T = array(); didn't work Commented Jun 10, 2014 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. Commented Jun 10, 2014 at 22:17

2 Answers 2

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'];
}
Sign up to request clarification or add additional context in comments.

Comments

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;
}

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.