14
Jun/06
44

Fatal error: Cannot use string offset as an array in …

PHP5 Error message that is caused by attempting to assign a value to an array element of a variable that is declared as a string.

Example that generates error:
$foo=’bar’;
$foo[0]=’bar’;
Get error message Fatal error: Cannot use string offset as an array in …

Explanation
$foo was declared as a string in $foo=’bar’.
$foo[0] is trying to append an element onto a string variable.

Example that does not generate error:
$foo[0]=’bar’;
$foo=’bar’;
Does NOT generate error.

Explanation
$foo[0]=’bar’ instantiates variable $foo as array since it has not been instantiated. Then assigns ‘bar’ to element $foo[0].
$foo=’bar’ implicitly re-declares $foo as a string and assigns ‘bar’ to it.

Example that does not generate error:
$foo=’bar’;
$foo=array();
$foo[0]=’bar’;

Explanation
$foo=’bar’ implicitly declares $foo as a string variable then assigns ‘bar’ as the value.
$foo=array() explicitly re-declares $foo as an array.
$foo[0]=’bar’ can now be executed as $foo is declared as an array.

Let me know if this helped you or if I am not clear on anything. Thanks.

Comments (44) Trackbacks (0)
  1. 20jfg
    3:54 pm on July 15th, 2007

    great stuff, really helped me out when getting this error with my session – thanks!

  2. electric_bit
    2:12 am on September 10th, 2007

    thanks, to help me solve this problem…

  3. CJJUNE
    6:51 am on October 2nd, 2007

    hi,

    I got the same fatal error on this line;-
    $eta_array = explode(”-”, $this->servicesTimeintransit[$type]["date"]);

    Do you know what is wrong with this line?
    i added $eta_array =array() before the line above still no difference

  4. frank
    12:24 am on October 4th, 2007

    Tough to diagnose with just that bit of info, but I wonder if your problem has to do with $this->servicesTimeintransit[$type][”date”]

    Does that matrix actually exist?

  5. CJJune
    5:32 am on October 4th, 2007

    Hi frank,

    Thanks. Actually its the error happens after PHP4 upgrade to PHP5. I think the matrix does exist as it work in PHP4 but not PHP5.

    How do I email you more on the code snippets?

  6. frank
    11:04 am on October 4th, 2007

    You can send me a message through the site.

  7. CJJune
    6:49 pm on October 4th, 2007

    Hi Frank,

    “Fatal error: Cannot use string offset as an array”
    appears in the code. Happened on this line $eta_array = explode(”-”, $this->servicesTimeintransit[$type]["date"]);

    More code snippets below:-

    $methods = array();
    for ($i=0; $i servicesTimeintransit[$type])) {

    $eta_array = explode(”-”, $this->servicesTimeintransit[$type]["date"]);
    $months = array (” “, “January”, “February”, “March”, “April”, “May”, “June”, “July”, “August”, “September”, “October”, “November”, “December”);
    $eta_arrival_date = $months[(int)$eta_array[1]].” “.$eta_array[2].”, “.$eta_array[0];
    $_type .= “, ETA: “.$eta_arrival_date;
    }
    // END of doing things differently:

    $methods[] = array(’id’ => $type, ‘title’ => $_type, ‘cost’ => ($this->handling_fee + $cost));
    }
    }

  8. frank
    10:27 pm on October 4th, 2007

    CJJune

    The first thing that I see a problem with is your for loop statement.

    for ($i=0; $i servicesTimeintransit[$type])) {

    It should be in the form of

    for ($i=0; $i<$var; $i++) {

    I think you are getting “Fatal error: Cannot use string offset as an array” because servicesTimeintransit[$type] is an array and not an int or string. I gathered that servicesTimeintransit[$type] is an array as you are calling servicesTimeintransit[$type]["date"] two lines down.

    I hope that helps.

  9. CJJune
    5:38 am on October 5th, 2007

    Hi frank,

    I am not too sure how to solve this as this code is not written by me. This code is from UPSXML.

    So what should I replace the line of code with to eliminate error?

  10. frank
    1:47 pm on October 5th, 2007

    Hmmm, if you did not write the code and have not changed anything, then you need to contact the creator of upsxml as the code that you have pasted is certainly incorrect in terms of the For loop.

    As for debugging the line $eta_array = explode(”-”, $this->servicesTimeintransit[$type][”date”]);

    try just returning the value to see what you are actually exploding by using

    echo($this->servicesTimeintransit[$type][”date”]);

  11. frank
    1:54 pm on October 5th, 2007

    I forgot to answer your question. I don’t know what you should replace the For loop declaration with as I don’t know the proper logic the author was intending. The current declaration posted

    for ($i=0; $i servicesTimeintransit[$type])) {

    does not give me any indication.

    I think someone has made a change to your code and you should find a backup copy to compare what has been change. Then move forward in debugging any further errors.

    I hope that helps.

  12. CJJune
    6:47 am on October 7th, 2007

    :-P

    I have no idea how?
    Could be Curl problem in PHP5 as it works in PHP4?

  13. frank
    10:44 am on October 10th, 2007

    You would have errors pointing to Curl if that was the issue.

  14. CJJune
    7:49 pm on October 18th, 2007

    Yeap….I guess its not CURL as the error is on the line of code pertaining to array. …:-(

  15. gb
    7:37 am on April 9th, 2008

    thank you for explanation ;)

  16. ramzi
    11:50 pm on June 13th, 2008

    Hi frank

    something weird happened on my website ( weird for me at least **blush****

    my website has been online for a year now.
    the, 2 days ago , for no reason, when someone makes a search on my website, it gives :

    Fatal error: Cannot use string offset as an array in /home/ramzi76/public_html/smartway/lib/system.lib on line 192

    first. why such errors are auto-generated? i mean no one touched the files or updated anything?

    now when i go to the said line, it is :
    return strtoupper($fMemb[ login ][ 0 ]).str_repeat(”0″, 6 – strlen($fMemb[ id ])).$fMemb[ id ];
    } // sysGetProfileCode

    where is the error?

    thx

  17. frank
    12:22 pm on June 16th, 2008

    ramzi,

    Something must have if it was working before and now you are getting an error. Changing from one version of php to another might have different results in how implicit declarations happen also. I am not sure how each version handles it as I have not done full research into that, but I’m sure you can Google it.

    One thing you can do debug your problem is to make sure
    $fMemb[ login ][ 0 ]
    $fMemb[ id ]
    are both set and are also strings. It is hard to tell from just looking at the code as we cannot see what those array elements hold at the time of the error. If you can post the echos of those array elements to show the strings values, then it would help in determining the problem of you situation.

  18. sshah254
    7:50 am on July 17th, 2008

    I have a variable $parts.

    $parts is as follows:
    Array
    (
    [0] => Array
    (
    [Part] => Array
    (
    [unit_price] => 9500.000000
    [id] => 0500-0300
    )

    [QuoteLine] => Array
    (
    )

    )

    )

    I get the error when I try to do this:

    printf(’%01.2f’, $parts[0]['Part']['unit_price']);

    Any pointers to solve this error are greatly appreciated.

    Thanks

  19. frank
    9:36 am on July 17th, 2008

    sshah,

    It looks like your array was not constructed properly. First, you need commas between array elements. Second, you need to use single quotes around the element index instead of brackets [ ].

    Also, the single quotes you have in the format parameter of printf are not the conventional single quotes. I am not sure if that would cause a problem too. It is worth sticking with convention for simplification.

    Below is the fixed code to form your array.
    ———————————-
    $parts = Array
    (
    Array
    (
    ‘Part’ => Array
    (
    ‘unit_price’ => 9500.000000,
    ‘id’ => 0500-0300
    ),

    ‘QuoteLine’ => Array
    (
    )

    )

    );

    printf(’%01.2f’, $parts[0]['Part']['unit_price']);
    ———————————-

    Hope that helps.

  20. frank
    9:39 am on July 17th, 2008

    sshah,

    About the single quote convention comment, I realized that wordpress could have changed them for styling when you entered your comment like it happened with my response. Never mind that statement then as you probably have it correct in your code.

  21. Grox
    2:53 am on August 30th, 2008

    Thank you. This was a fast help for me.

  22. Joyce
    10:33 am on September 8th, 2008

    Thanks :)

  23. Jeyaprakash
    6:58 am on November 4th, 2008

    This helped at the time I needed. It has saved me precious hours. thank you very much

  24. Cgarcia
    9:48 am on November 11th, 2008

    work for me too.. a no-exist-array hapens …. PHP4 dont report that… thanks

  25. lyndsey
    3:07 am on January 28th, 2009

    Thanks very much. Perfect answer

  26. barbogio
    12:34 pm on February 4th, 2009

    thanks! :)

  27. suhasini
    11:07 pm on February 5th, 2009

    Hi,
    I am also getting the error as “Cannot use a string as an offset array”

    I am using PHP 5.

    $FQL = “SELECT name, pic, uid FROM user where uid in (select uid2 from friend where uid1 = $hostid)”;
    $result_set = $facebook->api_client->fql_query($FQL);

    for($i=0;$i<$count;$i++)
    {
    $frid[]=$result_set[$i]['uid'];
    $frname[]=$result_set[$i]['name'];
    $frimg[]=$result_set[$i]['pic'];
    }
    What’s wrong in this code?

  28. frank
    11:37 pm on February 5th, 2009

    What is the value of $count? I don’t see that being set in your code.

  29. suhasini
    11:50 pm on February 5th, 2009

    $count is my friends count. It’s declared in my code.

    $count=sizeof($friends); // It’s coming as 9.

  30. suhasini
    12:02 am on February 6th, 2009

    Thanks Franks for your quick reply. My complete php code is:

    api_client;
    $friends = $api_client->friends_get();
    $hostid=$api_client->users_getLoggedInUser();
    $frname = array();
    $frimg=array();
    $frprofurl=array();
    $frid=array();
    $count=sizeof($friends);
    echo $count;
    $FQL = “SELECT name, pic, uid FROM user where uid in (select uid2 from friend where uid1 = $hostid)”;
    $result_set = $facebook->api_client->fql_query($FQL);

    foreach ($friends as $id)
    {
    $frprofurl[]=”http://www.facebook.com/profile.php?id=$id”;
    }
    for($i=0;$i

    Where I am going wrong?

  31. suhasini
    1:26 am on February 6th, 2009

    Frank, need quick help on this.

  32. frank
    9:52 am on February 6th, 2009

    Which line of code are you getting the error and is it the “fatal error cannot use string …” error?

  33. Lenz
    11:36 am on April 20th, 2009

    hey frank!
    i think i need your help, please :)

    i’m getting that same error and have no idea what i did wrong… check it out:

    foreach ($content[$main_section_id] as $feature_key => $feature_value) {
    echo("\n");
    //var_dump(is_int($feature_key));
    if($main_section_id == 'wasn')
    echo($feature_value);
    elseif($main_section_id == 'gd') {
    echo("\n");
    echo("\n");
    echo("
    stepcarousel.setup({
    galleryid: 'gallery$feature_key',
    beltclass: 'belt',
    panelclass: 'panel',
    panelbehavior: {speed:500, wraparound:true, persist:false},
    defaultbuttons: {enable: true, moveby: 1, leftnav: ['arrowl.gif', 0, 0], rightnav: ['arrowr.gif', 0, 0]},
    statusvars: ['reportA', 'reportB', 'reportC'],
    contenttype: ['inline'],
    onpanelclick: function(target){
    if (target.tagName=='IMG' && target.parentNode.tagName=='A'){
    $.ajax({
    url: '../js/gallery.php',
    data: 'tab=ILLUSTRATIONS',
    success: function(html){
    $('.preview').html(html);
    }
    });
    return false;
    }
    }
    })

    \n");

    foreach ($content[$main_section_id][$feature_key] as $content) {
    echo("$content\n");
    }
    echo("\n");
    echo("\n");

    echo("");

    }

    now, i’m getting the error at the second ‘foreach’ loop:
    foreach ($content[$main_section_id][$feature_key] as $content)

    i’m setting the arrays up in a separate file, which looks a bit like this:

    $data['main_section_ids'] = array("wasn", "gd", "wd", "c");

    $data['menu_items']['wasn'] = array('Welcome', 'About', 'Services', 'News');
    $data['menu_items']['gd'] = array('Illustrations', 'Editing', 'Logos');
    //$data['menu_items']['wd'] = null;

    $data['content']['wasn'][] = 'WELCOME';
    $data['content']['wasn'][] = 'ABOUT';
    $data['content']['wasn'][] = 'SERVICE';
    $data['content']['wasn'][] = 'NEWS';

    $data['content']['gd'][] = array('"', 'THINGS', 'OTHER THINGS', 'MORE STUFF');
    $data['content']['gd'][] = array('other things', 'more of the same');
    $data['content']['gd'][] = array('"', 'THINGS', 'OTHER THINGS', 'MORE STUFF');

    i’ve tried to explicitly enter integer keys myself but it doesn’t help… the weird thing is, that it loops through that second foreach (the one that give me the error) once but throws the error on the second try. it should loop thrice.

    any ideas!?

    thanks for your time!!!

  34. frank
    12:05 pm on April 20th, 2009

    Lenz,

    The line

    foreach ($content[$main_section_id][$feature_key] as $content)

    You are setting the value of $content[$main_section_id][$feature_key], which I assume is some kind of string, to the variable, $content, which is your source array. Then on the next time around the loop, $content is a string value but you are referring to it as if it is an array.

    Just change the above line of code to

    foreach ($content[$main_section_id][$feature_key] as $foo)

  35. Lenz
    12:15 pm on April 20th, 2009

    oohhhh, noooo! :P

    thanks, man!!!

    something about trees and forests comes to mind :P

    really appreciate it! thank you very much!

  36. frank
    12:41 pm on April 20th, 2009

    np. Glad I can help.

  37. baris
    4:37 am on August 25th, 2009

    i tried and it works perfectly but it takes very long time.

  38. jake
    8:38 am on December 22nd, 2009

    I am having a similar error.

    Using
    $client = new MyFunction($authToken, $billerID);
    $result = $client->GetTempToken(’3488178870172224′, “John Doe”, “120″, “Y”);

    I am trying to pull $result['result']['TempToken'] from the generated array below:

    Array
    (
    [result] => Array
    (
    [ResultCode] => 00
    [ResultMessage] =>
    [ResultValue] => SUCCESS
    [TempToken] => eb41d070-5f17-408f-aae7-09d0b971cc421b9fc5fe-490f-4cc6-8454-e99a658cf783
    [PayerId] => 1234567890123456
    [CredentialId] => 811884
    )
    )

    I dont know if it matters, but I also try pulling $result['result']['ExternalID'] from the following generated array and it works fine.

    Array
    (
    [result] => Array
    (
    [ResultCode] => 00
    [ResultMessage] =>
    [ResultValue] => SUCCESS
    [ExternalID] => 1234567890123456
    )
    )

    Since the ExternalID array works, I am at a loss as to why the TempToken array doesn’t work. I have tried running them as separate files with static content but I cannot seem to get it to work…

    Any ideas?
    Thanks

  39. frank
    9:57 am on January 6th, 2010

    Jake, try using single quotes around your string literals like ['TempToken']. Use them in both the creation of the array and retrieving an element from the array. That is one problem that I can identify immediately.

  40. tony
    1:19 am on January 20th, 2010

    Frank you are a saint to help everyone like this. Can you take a look at this piece of code? I noted the line I get the error from. The code runs fine at outputting the main page but when I try to submit a comment, I get the offset error on that line. It’s a wordpress custom theme, I left off the rest of the code as it is loops for outputting the posts. (I think :) ) Thanks

    $v) {
    $orderbydate[$v[0]['post_date']][$k] = $v;
    }

    krsort($orderbydate);
    foreach ($orderbydate as $k => $v) {
    ksort($orderbydate[$k], SORT_STRING);
    }
    }

  41. tony
    1:20 am on January 20th, 2010

    Ah man I don’t know what happened. Here is the code:

    $v) {
    $orderbydate[$v[0]['post_date']][$k] = $v;
    }

    krsort($orderbydate);
    foreach ($orderbydate as $k => $v) {
    ksort($orderbydate[$k], SORT_STRING);
    }
    }

  42. tony
    1:23 am on January 20th, 2010

    Maybe it’s appearing that way before it’s approved?
    Here is a smaller piece of code:
    $res = mysql_query($qry);
    if ($res) {
    while ($row = mysql_fetch_assoc($res)) {
    $author[$row['user_nicename']][] = $row; <–this line
    }

  43. frank
    9:53 am on January 20th, 2010

    Tony,

    Do the following
    echo $author[$row['user_nicename']]; //to see what you get

    I am guessing that it is already set as a string previously and that is why you are getting this “cannot use string offset as an array” error.

  44. tony
    10:05 pm on January 20th, 2010

    thanks frank! actually, the loop works fine unless I click to submit a comment. I define $author later in the code as a string so when it comes back to this part I think it still thinks it’s a string. I added $author=array(); and it seemed to sort things out. Now I’ve moved on to the main problem of the comment not inserting into the database! :)

Leave a comment

No trackbacks yet.