Uncaught TypeError: Cannot access offset of type string on string in

PHP 8.1.2
I have 2 arrays:

$Rex = array('');
$tfields = $db->fetch_assoc_all();

$tfields holds multiple records from an sql query.
I am trying to create an empty record in an indexed array of associative arrays. I just want the key but with no value. This statement worked with warnings on older versions of PHP:

  foreach($tfields as $key => $value)//use data from tfields to build next query
  { 
....
....
     $Rex[0][$value['ColName']] = '';//line that generates error
  }

But get the error mentioned above. It seems to imply that I am dealing with a string. Is $value not an array?

The problem is because $rex is an array with a single entry that is an empty string. You are trying to treat that empty string like it is an array. I suspect you just want $rex to be an empty array? $rex = [];

This indicates you are doing something wrong. If you are trying to get related data from a relational database, you should use a single JOIN query.

It seems that the error you are encountering is related to the fact that $value is not an array, but a string. This may be due to changes in the behavior of the fetch_assoc_all() method in more recent versions of PHP.

To resolve this error, you can modify your code to explicitly cast $value to an array:

Try this:

foreach ($tfields as $key => $value) {
$value = (array) $value; // explicitly cast $value to an array
$Rex[0][$value[‘ColName’]] = ‘’; // add empty value to the associative array
}

This should ensure that $value is treated as an array, even if it is originally returned as a string by the fetch_assoc_all() method.

If i didn’ misunderstand you this should work.

Yes the array declaration was wrong. I had $Rex = array(’’); but it should have been $Rex = array(); or as you did it $rex = [];

Thanks to both of you for helping me. Much appreciated :slight_smile:

The problem I mentioned, by itself, produces a slightly different fatal error (just tested.) I suspect there’s some conditional logic in the code that is assigning a value to $value (one =) vs testing what’s in $value (two ==), that is either no longer being executed due to the new $Rex initial value or got fixed too?

Sponsor our Newsletter | Privacy Policy | Terms of Service