0

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.

4
  • When provided $time does not match the pattern, the $matches will be an empty array. That will throw a "Undefined array key" error if you try access any index. Commented Jun 28, 2023 at 18:12
  • @AhmCho so what do i need to do to fix this? I need to assign something to $matches? I'm confused still on what needs to be done here. Commented Jun 30, 2023 at 20:08
  • The very first thing that comes in mind is just to check if $matches has any values (not empty) and then do your transformations. And if the the array is empty, your function may return the value as it is. Commented Jul 1, 2023 at 7:17
  • Does this answer your question? "Notice: Undefined variable", "Notice: Undefined index", "Warning: Undefined array key", and "Notice: Undefined offset" using PHP Commented Dec 21, 2023 at 10:51

1 Answer 1

-1

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;
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.