0

I'm working on some old PHP website and cannot figure out how to fix this kind of error:

Fatal error: Uncaught Error: Cannot use string offset as an array

This is the part where the error is being thrown

$ret["content"]["news"] = array();
$start = ($pagenum - 1) * $page_rows;
$stop = ($count > $start + $page_rows) ? $start + $page_rows : $count;

for($i = $start; $i < $stop; $i++)
{
    $cnt = sizeof($ret["content"]["news"]);
    print_r($ret);
    $ret["content"]["news"][$cnt] = $this->getPost($all[$i]);           
}

print_r returns

Array ( [content] => A [template] => intro )

Error is being thrown at this line

$ret["content"]["news"][$cnt] = $this->getPost($all[$i]);   

Full code source: https://pastebin.com/aPC2suL5

14
  • 2
    EXACTLY where is it being thrown? Commented Jul 9, 2018 at 12:25
  • 1
    what is the type of $ret["content"]["news"]? If not array it will throw error Commented Jul 9, 2018 at 12:25
  • 2
    var_dump($ret["content"]["news"]); Commented Jul 9, 2018 at 12:26
  • 4
    $ret["content"] is a string. What do you expect by adding [news]? Commented Jul 9, 2018 at 12:28
  • 1
    As has been mentioned, your code is setting $ret["content"] to various string values. $ret = array("content" => "", "template" => "intro"); and $ret["content"] = $this->getPost($_GET["id"]); and $ret["content"] = "Nothing here"; all do this. If you later want to make $ret["content"], then you probably need to initialize it as such first by doing $ret["content"] = array();. Commented Jul 9, 2018 at 12:36

1 Answer 1

1

Many parts of your code are type-swapping your variables; mixing arrays and strings. Try the below:

for($i = $start; $i < $stop; $i++)
{
   // Debug only. Remove once bugs are squashed. 
   if(!is_array($ret["content"])){
      error_log("You've set ret['content'] as a non-array; probably a string!");
    }  
    if(!is_array($ret["content"]["news"])){
        error_log("You've set ret['content']['news'] as a non-array too!");
    }
    //end debug block
    /***  
     * You do not need to count the array values each time, simply append with []
     ***/
    $ret["content"]["news"][] = $this->getPost($all[$i]);           
}
Sign up to request clarification or add additional context in comments.

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.