14 Jun 2006 @ 3:54 PM 
 

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.

Tags Categories: Coding Posted By: frank
Last Edit: 20 Apr 2009 @ 11 51 AM

E-mailPermalink
 

Responses to this post » (36 Total)

 
  1. 20jfg said...
    3:54 pm - July 15th, 2007

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

  2. electric_bit said...
    2:12 am - September 10th, 2007

    thanks, to help me solve this problem…

  3. CJJUNE said...
    6:51 am - 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 said...
    12:24 am - 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 said...
    5:32 am - 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 said...
    11:04 am - October 4th, 2007

    You can send me a message through the site.

  7. CJJune said...
    6:49 pm - 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 said...
    10:27 pm - 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 said...
    5:38 am - 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 said...
    1:47 pm - 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 said...
    1:54 pm - 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 said...
    6:47 am - October 7th, 2007

    :-P

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

  13. frank said...
    10:44 am - October 10th, 2007

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

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

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

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

    thank you for explanation ;)

  16. ramzi said...
    11:50 pm - 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 said...
    12:22 pm - 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 said...
    7:50 am - 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 said...
    9:36 am - 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 said...
    9:39 am - 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 said...
    2:53 am - August 30th, 2008

    Thank you. This was a fast help for me.

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

    Thanks :)

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

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

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

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

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

    Thanks very much. Perfect answer

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

    thanks! :)

  27. suhasini said...
    11:07 pm - 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 said...
    11:37 pm - February 5th, 2009

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

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

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

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

  30. suhasini said...
    12:02 am - 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 said...
    1:26 am - February 6th, 2009

    Frank, need quick help on this.

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

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

  33. Lenz said...
    11:36 am - 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 said...
    12:05 pm - 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 said...
    12:15 pm - 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 said...
    12:41 pm - April 20th, 2009

    np. Glad I can help.

 

Leave A Comment ...

 

 XHTML:
You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>
\/ More Options ...
Change Theme...
  • Role »
  • Posts »
  • Comments »
Change Theme...
  • VoidVoid (Default)
  • LifeLife
  • EarthEarth
  • WindWind
  • WaterWater
  • FireFire
  • LiteLightweight