0

Why does this code always give me an error "Illegal string offset 'list_img'"? Where have I made a mistake?

$dir = scandir($route);
for ($img = 0; $img < count($dir); $img++) {
    if ($dir[$img] == "." || $dir[$img] == "..") {
        continue;
    }
    $type = pathinfo($route . '/' . $dir[$img], PATHINFO_EXTENSION);
    $data = file_get_contents($route . '/' . $dir[$img]);
    $base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
    array_push($list_dir, ['title' => $dir[$img], 'code' => $base64]);
}
$data['list_img'] = $list_dir;
halfer
  • 19,824
  • 17
  • 99
  • 186
Reina Xie
  • 5
  • 3
  • Possible duplicate of [Reference — What does this symbol mean in PHP?](https://stackoverflow.com/questions/3737139/reference-what-does-this-symbol-mean-in-php) – Paul T. Sep 26 '18 at 02:25
  • Possible duplicate of [Reference - What does this error mean in PHP?](https://stackoverflow.com/questions/12769982/reference-what-does-this-error-mean-in-php) – miken32 Sep 26 '18 at 03:57

1 Answers1

0

Your variable $data is string (set with file_get_contents), so when you are trying to set $data['list_img'] you receive error. You can use other name instead of $data or initialize it as an array before last line:

$data = [];
$data['list_img'] = $list_dir

or just

$data = ['list_img' => $list_dir];
Dmitry Melnikov
  • 743
  • 4
  • 13