Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

handle null values to prevent errors while in loop

Tags:

php

I am using the following code to return data from a loop and although I am receiving the data it seems there may be null data also which is producing errors.

Here is the code

$extensions = count($cert['tbsCertificate']['extensions']);
for ($j = 0; $j < $extensions; $j++) {
    $count = count($cert['tbsCertificate']['extensions'][$j]['extnValue']);
    for ($i = 0; $i < $count; $i++) {
        if (array_key_exists('dNSName', $cert['tbsCertificate']['extensions'][$j]['extnValue'][$i])) {
            $value = $cert['tbsCertificate']['extensions'][$j]['extnValue'][$i]['dNSName'];
            $item = $i;
            echo 'DNSName',$item,'   : ', $value,"\n";
        }
    }
}

Here is the result of output

enter image description here

Can someone help me update the code to check for null values (i think in the first for loop) and ideally ignore those so the warnings don't appear? I am happy to provide more context if required.

like image 482
user3436467 Avatar asked Mar 06 '26 03:03

user3436467


1 Answers

Change your if condition so that it checks if it is set and if it is array first:

if(isset($cert['tbsCertificate']['extensions'][$j]['extnValue'][$i])
    &&
is_array($cert['tbsCertificate']['extensions'][$j]['extnValue'][$i])
    && 
array_key_exists('dNSName', $cert['tbsCertificate']['extensions'][$j]['extnValue'][$i]))

if it detects in first condition it is not set or is not an array, it will not proceed to array_key_exists function.

like image 146
n-dru Avatar answered Mar 07 '26 17:03

n-dru



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!