Warning: Undefined array key 1

2.3k views Asked by At

It only started giving me problems when i upgraded to php 8.1.

The issue is on the line $time = $matches

Although, this is a very generic question and probably has been answered quite a few time something similar. I looked through some of the other questions with a similar title but i'm still confused on what i need to do in my code particular.

   /**
         * Generates filtered time input from user to formatted time (YYYY-MM-DD)
         *
         * @param mixed $time
         * @return string
         */
        protected function filterTimeInput(mixed $time): string
        {
            $matches = [];
            preg_match('/(\d+-\d+-\d+)T(\d+:\d+)/', $time, $matches);
            $time = $matches[1] . " " . $matches[2];
            return strftime('%Y-%m-%d %H:%M:00', strtotime($time));
        }

Please any help would be greatly appreciated.

1

There are 1 answers

0
miRastic On

To fix the error I would use isset builtin of PHP or null coalesce operator

$match_1 = $matches[1] ?? ""; # Null coalesce example
$match_2 = isset($matches[2]) ? $matches[2] : ""; # isset example
$time = $match_1 . " " . $match_2;