phpcsvmultidimensional-arraywarningsphp-8.1

PHP 8.1 Warning: Trying to access array offset on value of type bool in array construction


I have a problem with the construction of an array which produces this error in PHP 8.1:

Warning: Trying to access array offset on value of type bool in C:\xampp\htdocs\sito3\xlsx.php on line 250

I eliminated the warning but I would like to understand how to get rid of it cleanly.

This is my function:

function dividi_nome_cognome(string $stringa): array 
{
    if (str_word_count($stringa, 1) === 2) {
        // only one separator " "
        return trim(explode(" ", $stringa));
    } else {
        // more than one separator
        return [
            trim(substr($stringa, 0, strrpos($stringa, " "))),
            trim(substr($stringa, strrpos($stringa, " "))),
        ];
    }
}

and the other function:

function csvToArray($csvFile,$separatore){
    
    $file_to_read = fopen($csvFile, 'r');
    
    while (!feof($file_to_read) ) {     
        $lines[] = fgetcsv($file_to_read, 1000, $separatore);       
    }
    
    fclose($file_to_read);
    return $lines;
}

I'm trying to build an array from a .csv file with separator ","

$arr_csv = csvToArray($nome_file_csv,',');
for($c=0; $c< count($arr_csv ); $c++){
                
//this line creates the warning
$nome_cognome_parts =  @divide_name_surname( ($arr_csv[$c][0] !== null) ? $arr_csv[$c][0] : "" );
$nome = $nome_cognome_parts[0];
$cognome = $nome_cognome_parts[1];
        
// build final array  
$array_finale[$c][0] = ""; 
$array_finale[$c][1] = "";
$array_finale[$c][2] = @$arr_csv[$c][2]; //this line creates the warning
$array_finale[$c][3] = @$arr_csv[$c][3]; //this line creates the warning
$array_finale[$c][4] = @$arr_csv[$c][0]; //this line creates the warning
$array_finale[$c][5] = "";
$array_finale[$c][6] = @$arr_csv[$c][1]; //this line creates the warning
$array_finale[$c][7] = "";
$array_finale[$c][8] = $nome;
$array_finale[$c][9] = $cognome;
$array_finale[$c][10] = $progressivo;
$array_finale[$c][11] = date("d-m-Y H:i:s");
$progressivo++;
}

How can I solve the problem without having to hide the warning?


Solution

  • The code may be trying to read non-existent lines at the end of the file.

    Follow the example in the official documentation to correctly read all the rows:

    function csvToArray($csvFile,$separatore){
        
        $file_to_read = fopen($csvFile, 'r');
        
        while (($data = fgetcsv($file_to_read, 1000, $separatore)) !== FALSE) {
            $lines[] = $data;       
        }
        
        fclose($file_to_read);
        return $lines;
    }