Please Help Me, How to Fix PHP Error Undefined Array Key “srcset”

Latest versions of PHP get mad if you try to reference array parameters that don’t exist. It’s a ‘warning’ type error, so the page will still load.

You need to test for existence of an array parameter before you reference it. So instead of

$attr['srcset'] = str_replace( array( '.jpeg' ), '.jpeg.webp', $attr['srcset'] );

Put those array references in an IF statement

if (isset($attr['srcset']) {
   $attr['srcset'] = str_replace( array( '.jpeg' ), '.jpeg.webp', $attr['srcset'] );
}

That will eliminate that warning message. You will have to do similar to all array elements that may not exist.

You also do something like this:

$attr['srcset'] = ($attr['srcset']) ? str_replace( array( '.jpeg' ), '.jpeg.webp', $attr['srcset'] ) : "";

Which will set that array element to blank if it doesn’t exist, so you won’t have to test for it the next time you use it.