Search code examples
phpundefinedoffset

How to fix undefined offset: 1


How can I solve this issue (undefined offset: 1 at line 30):

$imagesarray = array();
        while($file = readdir($handle)){
            if($file !== '.' && $file !== '..'){
                $fileArr = explode('.', $file );
<<line 30>>             if ( $fileArr[1] == 'jpg' || $fileArr[1] == 'jpeg' || $fileArr[1] == 'png' || $fileArr[1] == 'gif' ){
                    array_push($imagesarray,$file);
                }
            }
        }

I want to upgrade to php8 but gets this in php 7,4 (php8 displays a slightly different outout)


Solution

  • Can be fixed with this:

    if (in_array($fileArr[1] ?? '',['jpg','jpeg','png','gif'],true)){
    

    $fileArr[1] ?? '' prevents undefined error

    in_array keeps the if statement short & clean