coder_hasib
coder_hasib

Reputation: 21

Got this error message Warning: Illegal string offset and Warning: Uninitialized string offset 11

I got this error every time run the application. I got everything ok. I have checked every steps and I got nothing. is it for php update ? I am using php 8. Here is my code.

class ViewProducts extends AddNewProduct
{
    private $to_array2, $to_array1;

    public function viewAllProducts() {
        // get image name
        $text_path = $this->getTextFilePath();

        //extract file contents
        $file_contents = file_get_contents($text_path);

        // convert string to array
        $this->to_array1 = explode('$', $file_contents);

        foreach ($this->to_array1 as $item => $value) {
            $this->to_array2 = explode(',', $value);

            if(isset($this->to_array2[0])){
                echo '<pre>';
                var_dump($this->to_array2[$item][$value]);
                echo '</pre>';
                //$to_array[$item]['id'] = $this->to_array2[0];
                //$to_array[$item]['name'] = $this->to_array2[1];
            } else {
                echo 'Nothing found';
            }
        }

        return $this->to_array2;
    }
}

Error details:

Please fill with data.


Warning:  Uninitialized string offset 11 in D:\PROJECTS\IDE\xampp\htdocs\tenth-project\app\classes\ViewProducts.php on line 24

string(0) ""

Fatal error:  Uncaught TypeError: Cannot access offset of type string on string in D:\PROJECTS\IDE\xampp\htdocs\tenth-project\app\classes\ViewProducts.php:24
Stack trace:
#0 D:\PROJECTS\IDE\xampp\htdocs\tenth-project\pages\action.php(24): App\classes\ViewProducts->viewAllProducts()
#1 {main}
  thrown in D:\PROJECTS\IDE\xampp\htdocs\tenth-project\app\classes\ViewProducts.php on line 24

Upvotes: 1

Views: 436

Answers (1)

IMSoP
IMSoP

Reputation: 97718

Look carefully at these two lines:

this->to_array2 = explode(',', $value);

And:

var_dump($this->to_array2[$item][$value]);

You have a string, which you split into a list of parts; you then try to access that list as though it was a two-dimensional array, using the original string as one of the keys. This doesn't even begin to make sense.

Unless you've changed them to hide details of the real program, one of your problems is probably that your variable names are poorly chosen. See how much clearer this is:

    $item_list = explode('$', $file_contents);

    foreach ($item_list as $item_number => $item_details) {
        $field_list = explode(',', $item_details);

        if(isset($field_list[0])){
            echo '<pre>';
            var_dump($field_list[$item_number][$item_details]); // clearly nonsense
            echo '</pre>'!
        } else {
            echo 'Nothing found';
        }
    }

With knowledge of what the program is actually doing, you can probably do better than "item" and "field".

Upvotes: 1

Related Questions