r/PHPhelp • u/Ok_Strike9189 • May 11 '26
turning fatal error back to warning when array index is not defined.
I have code that was working well in php 5.6 but now php 8.4 is complaining.
I narrowed the code down as follows:
if (isset($d{1})){echo "yay";}
the new PHP doesn't like curly braces so I fixed that with something slower:
if (isset($d)&&strlen($d)>1){echo "yay";}
But the one that's really frustrating is this one:
echo somefunction($d['name']);
In an old PHP version, if 'name' isn't set in the $d array or $d is not an array, then the parameter going into the function is null and I get a warning. but in php 8.4, I get this fatal error:
PHP Fatal error: Uncaught TypeError: Cannot access offset of type string on string in
Apparently this error doesn't happen in the php 7 and I heard php 7 is obsolete.
Is there a setting I can use in the php 8 config file to turn that fatal error into a warning again so my program can run? without me having to sift through my thousands of lines of code to change each index manually?
13
u/MateusAzevedo May 11 '26
That fatal error is telling that
$dis astringand not anarray. It doesn't make any sense to try to access anameindex on a string.It seems your code is very badly written, with no control whatsoever about the data types it's dealing with. Migrating it will be hard task and no, there isn't any setting you can change to get "old PHP behaviour back".
You can try Rector to automate most of the changes needed, but I'm not sure it'll be 100% accurate in your case.
7
u/mikkolukas May 12 '26
Your code is bad.
Fix it instead of trying to make PHP bend backwards to compensate.
4
u/eurosat7 May 11 '26
What is var_dump($d); giving you?
6
u/colshrapnel May 11 '26
Speaking of strings, the new PHP is OK with square braces though, so you can have it your way, just straighten the braces
While speaking of arrays - no, there is no such setting. The question is, why would you have an array defined as a string in the first place.
It's not the index you have to fix, but the variable definition
will give you your beloved Warning. Whereas
gives you exact Fatal error you are talking about.
1
u/Basic_Reporter9579 May 11 '26
why not use is_array($d)?
0
u/miqrogroove May 11 '26 edited May 11 '26
You're likely looking for the null coalescing operator to substitute the invalid variable for a default string.
echo ($d['name'] ?? 'default');
Note you can take this further with type juggling. I say this because the question vaguely stated "$d is not an array".
echo ($d['name'] ?? (string) $d);
0
u/HongPong May 11 '26
clean it up with gettype and enforce strict types on that file? https://www.php.net/manual/en/function.gettype.php
-1
u/th00ht May 11 '26
That's what regular expressions are for. Use regex101.com or AI to let a computer sift through billion lines of code and replace.
-4
u/[deleted] May 12 '26 edited May 12 '26
[removed] — view removed comment