Asked  7 Months ago    Answers:  5   Viewed   311 times

I get a strange PHP error after updating my php version to 5.4.0-3.

I have this array:

Array
(
    [host] => 127.0.0.1
    [port] => 11211
)

When I try to access it like this I get strange warnings

 print $memcachedConfig['host'];
 print $memcachedConfig['port'];


 Warning: Illegal string offset 'host' in ....
 Warning: Illegal string offset 'port' in ...

I really don't want to just edit my php.ini and re-set the error level.

 Answers

67

Please try this way.... I have tested this code.... It works....

$memcachedConfig = array("host" => "127.0.0.1","port" => "11211");
print_r($memcachedConfig['host']);
Wednesday, March 31, 2021
 
ariel
answered 7 Months ago
81

Assuming $img_tag is an object of some type, rather than a proper string, cast $img_tag to a string inside the []

preg_match_all("/(alt|title|src)=('[^']*')/i",(string)$img_tag, $img[(string)$img_tag]);
//------------------------------------------------------------------^^^^^^^^^

Some object types, notably SimpleXMLElement for example, will return a string representation to print/echo via the magic method __toString(), but cannot stand in as regular strings. Attempts to use them as array keys will yield the illegal offset type error unless you cast them to proper strings via (string)$obj.

Wednesday, March 31, 2021
 
Pwner
answered 7 Months ago
86

You could also have a look at set_error_handler to set your own error handler for this specific case, and then restore the error handler after making the function call.

Wednesday, March 31, 2021
 
TheFrack
answered 7 Months ago
69

Try:

$selected_fonts = array(
    $body_font,
    $heading_font,
    $menu_nav_font,
);

As $body_font, $heading_font and $menu_nav_font are string, using those as array will produce the warnings.

EDIT:

To be more generic:

$selected_fonts = array(
    is_array($body_font) && isset($body_font['face']) ? $body_font['face'] : $body_font,
    is_array($heading_font) && isset($heading_font['face']) ? $heading_font['face'] : $heading_font,
    is_array($menu_nav_font) && isset($menu_nav_font['face']) ? $menu_nav_font['face'] : $menu_nav_font,
);
Friday, May 28, 2021
 
viper
answered 5 Months ago
60

You need to make sure, that $meta is actually of type array. The warning explicitly tells you, that $meta seems to be a string and not an array

Illegal string offset
        ^^^^^^

To avoid this error you may also check for the needed fields

for($i = 0; $i < 3; $i++) {
    if ( !is_array($meta) || !array_key_exists('quote'. ($i+1), $meta) ){
         continue;
    }
    // your code
}
Friday, August 6, 2021
 
brabertaser19
answered 3 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :