Illegal string offset - I'm feeling dumb today

Discussion in 'PHP' started by PoPSiCLe, Apr 22, 2016.

  1. #1
    Okay - so, I'm trying to rewrite some stuff, and happen upon an error that I don't really understand why is showing - I'm doing something wrong, of course, but today I don't think my brain is working as it should.

    Okay, this is a var_dump of $_POST:
    
    array(5) {
    ["userid"]=>
    string(1) "1"
    ["nkid"]=>
    array(2) {
    [1]=>
    string(1) "1"
    ["new"]=>
    string(3) "new"
    }
    ["nk_name"]=>
    array(2) {
    [1]=>
    string(9) "Testadmin"
    ["new"]=>
    string(19) "Admin Senior Senior"
    }
    ["nk_phone"]=>
    array(2) {
    [1]=>
    string(7) "1234567"
    ["new"]=>
    string(8) "12345678"
    }
    ["nk_email"]=>
    array(2) {
    [1]=>
    string(13) "test@cntrl.no"
    ["new"]=>
    string(18) "admins@example.com"
    }
    }
    
    Code (markup):
    Each of the $_POST-arrays are turned into their own, separate arrays (by some handler-function), and this is a dump of $nk_name:
    
    array(2) {
    [1]=>
    string(9) "Testadmin"
    ["new"]=>
    string(19) "Admin Senior Senior"
    }
    
    Code (markup):
    All is well so far.
    However, if I do this:
    
    foreach ($nkid as $key => $value) {
      $nkid = $key;
      $nk_name = $nk_name[$key];
    }
    
    Code (markup):
    I get an "Illegal string offset - 'new'"-error on the line with $nk_name - and I can't seem to figure out _why_ - the $nk_name is an array, and it contains a 'new' key, so why doesn't it work?
     
    PoPSiCLe, Apr 22, 2016 IP
  2. sarahk

    sarahk iTamer Staff

    Messages:
    28,803
    Likes Received:
    4,534
    Best Answers:
    123
    Trophy Points:
    665
    #2
    can you give us a dump of $nkid?
     
    sarahk, Apr 22, 2016 IP
  3. PoPSiCLe

    PoPSiCLe Illustrious Member

    Messages:
    4,623
    Likes Received:
    725
    Best Answers:
    152
    Trophy Points:
    470
    #3
    And... wow. Yup, I do feel dumb. Assigning something to an existing array... yeah. Noticed it right after I posted, was sure I already tested that, but... nope, I didn't. So, for those who don't follow: The solution is to not use the same variable name as the damn array you're trying to pull data from. *HEADDESK*
     
    PoPSiCLe, Apr 22, 2016 IP
    sarahk likes this.
  4. PoPSiCLe

    PoPSiCLe Illustrious Member

    Messages:
    4,623
    Likes Received:
    725
    Best Answers:
    152
    Trophy Points:
    470
    #4
    The $nkid was basically just
    array (2) {
    1 => 1
    "new" => "new"
    }

    But, as you can see, I found the solution. Now I want to kill myself.
     
    PoPSiCLe, Apr 22, 2016 IP
    sarahk likes this.