简体   繁体   中英

Error : Trying to access array offset on value of type int

I have a problem with the error message "Trying to access array offset on the value of type int" I use PHP version 7.4, as I see on the web:

Array-style access of non-arrays

bool, int, float or resource as an array (such as $null["key"]) will now generate a notice.

Code is:

 <?php
        foreach($gdata_worksheets As $key => $value ){
            //$key="1361298261";
        ?>
            <option value="<?php echo strToHex($key); ?>"<?php echo $key == $gdata->worksheet_id ? ' selected="selected"' : ''?>><?php echo htmlentities($value, ENT_QUOTES, 'UTF-8');?></option>
            



function strToHex($string){

$hex = '';
for ($i=0; $i<strlen($string); $i++){
    $ord = ord($string[$i]);
    $hexCode = dechex($ord);
    $hex .= substr('0'.$hexCode, -2);
}
return strToUpper($hex);

}

How solve this, any idea?

Regards

$key is probably not a string, you can use gettype() to check.

You can access to number digits with substr() :

for ($i=0; $i<strlen($string); $i++){
    $ord = ord(substr($string, $i, 1));

If you prefer use array-access you must cast $string to (string) :

function strToHex($string){
    $string = (string)$string;

A final propal could be:

function strToHex($string)
{
    $result = '';
    $n = strlen($string);
    for ($i = 0; $i < $n; $i++) {
        $c = substr($string, $i, 1);
        $c = ord($c);
        $result .= sprintf('%02X', $c);
    }
    return $result;
}

echo strToHex(1234); // 31323334
echo strToHex('Yop!'); // 596F7021

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM