PHP Compile Error: "Cannot use empty array elements in arrays"

Solution 1:

This error, which is not documented anywhere I can find online, comes from having two commas in a row with nothing between them inside the array.

In my case, this actually appeared on line 42 of the file, not line 4 as indicated by the error message, which sounds like a bug in the compiler which identifies the first item in the array instead of the actual location of the "empty array element".


NOTE: In PHP 7.2.15+, 7.3.2+, and 7.4.0+, the error message has been changed to report the line number of the previous valid element instead of the line number of the beginning of the array. While this may still be off by one or more lines, it is usually close enough to the problem to make it much easier to find.

Solution 2:

I got the same error, while pointing at line 2, the error was on line 6.

I spent hours troubleshooting helplessly because it was a familiar code and I didn't know when an extra , got at the back of 'available' => $faker->boolean(85),

return [
  'id'          => $id,
  'user_id'     => $id,
  'slug'        => $slug,
  'speciality'  => $faker->randomElement(['Option A','Optoin B']),
  'available'   => $faker->boolean(85),,
  'subscription_ends_at' => $faker->dateTimeBetween('-5 day', '30 day'),
  'verified_at' => $faker->dateTimeBetween('-50 day', '-16 minute'),
];

Simply search your code for ,, or spaces between two commas , , on the same line as pointed out by @Moshe Katz.

This thread is a life saver.

Solution 3:

I got this error and yes, the line indicated as where the error happened was wrong(Error was on line 10 instead of line 2 of the code below):

return Http::response(
        ["popularity" => 113.485,
        "vote_count" => 9016,
        "video" => false,
        "poster_path" => "/qa6HCwP4Z15l3hpsASz3auugEW6.jpg",
        "id" => 920,
        "adult" => false,
        "backdrop_path" => "/8KeWhoMpqbzZRyHPkTtWSLWkL5L.jpg",
        "original_language" => "en",
        "original_title" => "Cars",
        "genre_ids" => [,
          0 => 12,
          1 => 16,
          2 => 35,
          3 => 10751,
        ],
        "title" => "Cars",
        "vote_average" => 6.8,
        "overview" => "Lightning McQueen, a hotshot rookie race car driven to succeed, discovers that life is about the journey, not the finish line, when he finds himself unexpectedly detoured in the sleepy Route 66 town of Radiator Springs. On route across the country to the big Piston Cup Championship in California to compete against two seasoned pros, McQueen gets to know the town's offbeat characters.",
        "release_date" => "2006-06-08",
    ]);

The issue was from a typo where I added a comma after the square bracket resulting in "[,"

So if you try the suggestions above and it doesn't work, look for a "[," and remove the trailing comma.