How do I prevent the Undefined offset:1 Error Exception in php

  laravel, php

I have the following code for importing excel data in my Controller

$row['cast'] = "Directed by:Tracie Pang;Written by:Dennis Kelly;Starring:Pinky Amador,Thomas Pang,Tess Pang,Salif Hardie";

$cast_types = explode(";", $row['cast']);
foreach ($cast_types as $cast_type) {
    $cast = explode(":", $cast_type);
    $cast_type_name = $cast[0];

    // if there is more than 1 cast name
    if (strpos($cast[1], ",") !== false) {
        $cast_names = explode(",", $cast[1]);
        $cast_names_str = implode("<br>", $cast_names);
    } else {
        $cast_names_str = $cast[1];
    }

$cast[1] will look something like "Tracie Pang" or "Pinky Amador,Thomas Pang,Tess Pang" (managed to see it also by running dd($cast[1]) ) but Laravel throws me an "Error Exception : Undefined Offset 1" here

if (strpos($cast[1], ",") !== false) {

How can I prevent this error?

Source: Ask PHP

LEAVE A COMMENT