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

Time:12-29

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

CodePudding user response:

$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('X', $c);
    }
    return $result;
}

echo strToHex(1234); // 31323334
echo strToHex('Yop!'); // 596F7021
  •  Tags:  
  • php
  • Related