Trying to access array offset on value of type null

最近把十幾年前的php code重構,原本在實現以下代碼時是正常運行的。

$file_show = mysqli_query($link,$file_show) or die('Query failed:'. mysqli_error());$file_row=mysqli_fetch_array($file_show);echo $file_row[0];$print_name = $target_row[2];if($file_row[0] == "ntof"){  $treechange = 1;  $upnodename = $file_row[2];}else{  $treechange = 0;  $upnodename = $target_row[2];}

後來換到PHP 7.4.16出現這個錯誤。

上stackoverflow查了一下,

ArSeN says:

his happens because $cOTLdata is not null but the index 'char_data' does not exist. Previous versions of PHP may have been less strict on such mistakes and silently swallowed the error / notice while 7.4 does not do this anymore.

To check whether the index exists or not you can use isset():

isset($cOTLdata['char_data'])

Which means the line should look something like this:

$len = isset($cOTLdata['char_data']) ? count($cOTLdata['char_data']) : 0;

Note I switched the then and else cases of the ternary operator since === null is essentially what isset already does (but in the positive case).

換句話說就是原本就是個問題,以前沒有顯示而已,那麼我們只要在使用該變數前使用 isset()方法來判斷是否為null即可。

if(isset($file_row[0])){if($file_row[0] == "ntof"){$treechange = 1;$upnodename = $file_row[2];}else{$treechange = 0;$upnodename = $target_row[2];}}

改完後再次運行就正常顯示資料囉!

Refer from https://stackoverflow.com/questions/59336951/message-trying-to-access-array-offset-on-value-of-type-null

喜歡我的文章請給予我拍手鼓勵~