doyp9057
2009-12-09 13:41
浏览 165
已采纳

不能在php中使用字符串偏移量作为数组

I'm trying to simulate this error with a sample php code but haven't been successful. Any help would be great.

"Cannot use string offset as an array"

图片转代码服务由CSDN问答提供 功能建议

我正在尝试使用示例php代码模拟此错误,但尚未成功。 任何帮助都会很棒。

“不能将字符串偏移用作数组”

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

9条回答 默认 最新

  • dtoaillwk759656786 2009-12-09 13:42
    已采纳

    For PHP4

    ...this reproduced the error:

    $foo    = 'bar';
    $foo[0] = 'bar';
    

    For PHP5

    ...this reproduced the error:

    $foo = 'bar';
    
    if (is_array($foo['bar']))
        echo 'bar-array';
    if (is_array($foo['bar']['foo']))
        echo 'bar-foo-array';
    if (is_array($foo['bar']['foo']['bar']))
        echo 'bar-foo-bar-array';
    

    (From bugs.php.net actually)

    Edit,

    so why doesn't the error appear in the first if condition even though it is a string.

    Because PHP is a very forgiving programming language, I'd guess. I'll illustrate with code of what I think is going on:

    $foo = 'bar';
    // $foo is now equal to "bar"
    
    $foo['bar'] = 'foo';
    // $foo['bar'] doesn't exists - use first index instead (0)
    // $foo['bar'] is equal to using $foo[0]
    // $foo['bar'] points to a character so the string "foo" won't fit
    // $foo['bar'] will instead be set to the first index
    // of the string/array "foo", i.e 'f'
    
    echo $foo['bar'];
    // output will be "f"
    
    echo $foo;
    // output will be "far"
    
    echo $foo['bar']['bar'];
    // $foo['bar'][0] is equal calling to $foo['bar']['bar']
    // $foo['bar'] points to a character
    // characters can not be represented as an array,
    // so we cannot reach anything at position 0 of a character
    // --> fatal error
    
    打赏 评论
  • douci1196 2011-12-20 20:12

    I just want to explain my solving for the same problem.

    my code before(given same error):

    $arr2= ""; // this is the problem and solve by replace this $arr2 = array();
    for($i=2;$i<count($arrdata);$i++){
        $rowx = explode(" ",$arrdata[$i]);
        $arr1= ""; // and this is too
        for($x=0;$x<count($rowx);$x++){
            if($rowx[$x]!=""){
                $arr1[] = $rowx[$x];
            }
        }
        $arr2[] = $arr1;
    }
    for($i=0;$i<count($arr2);$i++){
        $td .="<tr>";
        for($j=0;$j<count($hcol)-1;$j++){
            $td .= "<td style='border-right:0px solid #000'>".$arr2[$i][$j]."</td>"; //and it's($arr2[$i][$j]) give an error: Cannot use string offset as an array
        }
        $td .="</tr>";
    }
    

    my code after and solved it:

    $arr2= array(); //change this from $arr2="";
    for($i=2;$i<count($arrdata);$i++){
        $rowx = explode(" ",$arrdata[$i]);
        $arr1=array(); //and this
        for($x=0;$x<count($rowx);$x++){
            if($rowx[$x]!=""){
                $arr1[] = $rowx[$x];
            }
        }
        $arr2[] = $arr1;
    }
    for($i=0;$i<count($arr2);$i++){
        $td .="<tr>";
        for($j=0;$j<count($hcol)-1;$j++){
            $td .= "<td style='border-right:0px solid #000'>".$arr2[$i][$j]."</td>";
        }
        $td .="</tr>";
    }
    

    Thank's. Hope it's helped, and sorry if my english mess like boy's room :D

    打赏 评论
  • dongshenchi5364 2012-04-13 12:20

    I was fighting a similar problem, so documenting here in case useful.

    In a __get() method I was using the given argument as a property, as in (simplified example):

    function __get($prop) {
         return $this->$prop;
    }
    

    ...i.e. $obj->fred would access the private/protected fred property of the class.

    I found that when I needed to reference an array structure within this property it generated the Cannot use String offset as array error. Here's what I did wrong and how to correct it:

    function __get($prop) {
         // this is wrong, generates the error
         return $this->$prop['some key'][0];
    }
    
    function __get($prop) {
         // this is correct
         $ref = & $this->$prop;
         return $ref['some key'][0];
    }
    

    Explanation: in the wrong example, php is interpreting ['some key'] as a key to $prop (a string), whereas we need it to dereference $prop in place. In Perl you could do this by specifying with {} but I don't think this is possible in PHP.

    打赏 评论
  • douyi1982 2014-08-01 11:19

    When you directly print print_r(($value['<YOUR_ARRAY>']-><YOUR_OBJECT>)); then it shows this fatal error Cannot use string offset as an object in. If you print like this

    $var = $value['#node']-><YOU_OBJECT>; print_r($var);

    You won't get the error!!

    打赏 评论
  • dsf11t5u1651 2014-10-14 11:42

    I believe what are you asking about is a variable interpolation in PHP.

    Let's do a simple fixture:

    $obj = (object) array('foo' => array('bar'), 'property' => 'value');
    $var = 'foo';
    

    Now we have an object, where:

    print_r($obj);
    

    Will give output:

    stdClass Object
        (
            [foo] => Array
                (
                    [0] => bar
                )
    
            [property] => value
        )
    

    And we have variable $var containing string "foo".

    If you'll try to use:

    $give_me_foo = $obj->$var[0];
    

    Instead of:

    $give_me_foo = $obj->foo[0];
    

    You get "Cannot use string offset as an array [...]" error message as a result, because what you are trying to do, is in fact sending message $var[0] to object $obj. And - as you can see from fixture - there is no content of $var[0] defined. Variable $var is a string and not an array.

    What you can do in this case is to use curly braces, which will assure that at first is called content of $var, and subsequently the rest of message-sent:

    $give_me_foo = $obj->{$var}[0];
    

    The result is "bar", as you would expect.

    打赏 评论
  • dongxuan1660 2015-04-02 08:47

    The error occurs when:

    $a = array(); 
    $a['text1'] = array();
    $a['text1']['text2'] = 'sometext';
    

    Then

    echo $a['text1']['text2'];     //Error!!
    

    Solution

    $b = $a['text1'];
    echo $b['text2'];    // prints: sometext
    

    ..

    打赏 评论
  • doupang3062 2017-11-02 17:31

    I was able to reproduce this once I upgraded to PHP 7. It breaks when you try to force array elements into a string.

    $params = '';
    foreach ($foo) {
      $index = 0;
      $params[$index]['keyName'] = $name . '.' . $fileExt;
    }
    

    After changing:

    $params = '';
    

    to:

    $params = array();
    

    I stopped getting the error. I found the solution in this bug report thread. I hope this helps.

    打赏 评论
  • dsfsdf7852 2018-05-20 16:23

    I was having this error and a was nuts

    my code was

    $aux_users='';
    
    foreach ($usuarios['a'] as $iterador) { 
    #code
    if ( is_numeric($consultores[0]->ganancia) ) {
        $aux_users[$iterador]['ganancia']=round($consultores[0]->ganancia,2);
      }
    }
    

    after changing $aux_users=''; to $aux_users=array();

    it happen to my in php 7.2 (in production server!) but was working on php 5.6 and php 7.0.30 so be aware! and thanks to Young Michael, i hope it helps you too!

    打赏 评论
  • duanaoreng9355 2019-02-07 21:38

    I had this error for the first time ever while trying to debug some old legacy code, running now on PHP 7.30. The simplified code looked like this:

    $testOK = true;
    
    if ($testOK) {
        $x['error'][] = 0;
        $x['size'][] = 10;
        $x['type'][] = 'file';
        $x['tmp_name'][] = 'path/to/file/';
    }
    

    The simplest fix possible was to declare $x as array() before:

    $x = array();
    
    if ($testOK) {
        // same code
    }
    
    打赏 评论

相关推荐 更多相似问题