Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Illegal string offset Warning PHP

Tags:

php

warnings

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.

like image 950
thesonix Avatar asked Mar 26 '12 08:03

thesonix


15 Answers

The error Illegal string offset 'whatever' in... generally means: you're trying to use a string as a full array.

That is actually possible since strings are able to be treated as arrays of single characters in php. So you're thinking the $var is an array with a key, but it's just a string with standard numeric keys, for example:

$fruit_counts = array('apples'=>2, 'oranges'=>5, 'pears'=>0);
echo $fruit_counts['oranges']; // echoes 5
$fruit_counts = "an unexpected string assignment";
echo $fruit_counts['oranges']; // causes illegal string offset error

You can see this in action here: http://ideone.com/fMhmkR

For those who come to this question trying to translate the vagueness of the error into something to do about it, as I was.

like image 164
Kzqai Avatar answered Oct 02 '22 08:10

Kzqai


You're trying to access a string as if it were an array, with a key that's a string. string will not understand that. In code we can see the problem:

"hello"["hello"];
// PHP Warning:  Illegal string offset 'hello' in php shell code on line 1

"hello"[0];
// No errors.

array("hello" => "val")["hello"];
// No errors. This is *probably* what you wanted.

In depth

Let's see that error:

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

What does it say? It says we're trying to use the string 'port' as an offset for a string. Like this:

$a_string = "string";

// This is ok:
echo $a_string[0]; // s
echo $a_string[1]; // t
echo $a_string[2]; // r
// ...

// !! Not good:
echo $a_string['port'];
// !! Warning: Illegal string offset 'port' in ...

What causes this?

For some reason you expected an array, but you have a string. Just a mix-up. Maybe your variable was changed, maybe it never was an array, it's really not important.

What can be done?

If we know we should have an array, we should do some basic debugging to determine why we don't have an array. If we don't know if we'll have an array or string, things become a bit trickier.

What we can do is all sorts of checking to ensure we don't have notices, warnings or errors with things like is_array and isset or array_key_exists:

$a_string = "string";
$an_array = array('port' => 'the_port');

if (is_array($a_string) && isset($a_string['port'])) {
    // No problem, we'll never get here.
    echo $a_string['port'];
}

if (is_array($an_array) && isset($an_array['port'])) {
    // Ok!
    echo $an_array['port']; // the_port
}

if (is_array($an_array) && isset($an_array['unset_key'])) {
    // No problem again, we won't enter.
    echo $an_array['unset_key'];
}


// Similar, but with array_key_exists
if (is_array($an_array) && array_key_exists('port', $an_array)) {
    // Ok!
    echo $an_array['port']; // the_port
}

There are some subtle differences between isset and array_key_exists. For example, if the value of $array['key'] is null, isset returns false. array_key_exists will just check that, well, the key exists.

like image 35
Jon Surrell Avatar answered Oct 02 '22 07:10

Jon Surrell


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

$memcachedConfig = array("host" => "127.0.0.1","port" => "11211");
print_r($memcachedConfig['host']);
like image 35
letsnurture Avatar answered Oct 02 '22 09:10

letsnurture


There are a lot of great answers here - but I found my issue was quite a bit more simple.

I was trying to run the following command:

$x['name']   = $j['name'];

and I was getting this illegal string error on $x['name'] because I hadn't defined the array first. So I put the following line of code in before trying to assign things to $x[]:

$x = array();

and it worked.

like image 21
Brian Powell Avatar answered Oct 02 '22 08:10

Brian Powell


A little bit late to the question, but for others who are searching: I got this error by initializing with a wrong value (type):

$varName = '';
$varName["x"] = "test"; // causes: Illegal string offset

The right way is:

 $varName = array();
 $varName["x"] = "test"; // works
like image 33
Marco Avatar answered Oct 02 '22 07:10

Marco


As from PHP 5.4 we need to pass the same datatype value that a function expects. For example:

function testimonial($id); // This function expects $id as an integer

When invoking this function, if a string value is provided like this:

$id = $array['id']; // $id is of string type
testimonial($id); // illegal offset warning

This will generate an illegal offset warning because of datatype mismatch. In order to solve this, you can use settype:

$id = settype($array['id'],"integer"); // $id now contains an integer instead of a string
testimonial($id); // now running smoothly
like image 28
Anirudh Sood Avatar answered Oct 02 '22 08:10

Anirudh Sood


Before to check the array, do this:

if(!is_array($memcachedConfig))
     $memcachedConfig = array();
like image 31
dlopezgonzalez Avatar answered Oct 02 '22 09:10

dlopezgonzalez


In my case i change mysql_fetch_assoc to mysql_fetch_array and solve. It takes 3 days to solve :-( and the other versions of my proyect run with fetch assoc.

like image 40
Pichitron Avatar answered Oct 02 '22 09:10

Pichitron


In my case, I solved it when I changed in function that does sql query after: return json_encode($array) then: return $array

like image 34
Kleber Caldas Avatar answered Oct 02 '22 07:10

Kleber Caldas


It works to me:

Testing Code of mine:

$var2['data'] = array ('a'=>'21','b'=>'32','c'=>'55','d'=>'66','e'=>'77');
foreach($var2 as $result)
{  
    $test = $result['c'];
}
print_r($test);

Output: 55

Check it guys. Thanks

like image 40
Y. Joy Ch. Singha Avatar answered Oct 02 '22 09:10

Y. Joy Ch. Singha


just use

$memcachedConfig = array();

before

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


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

this is because you never define what is $memcachedConfig, so by default are treated by string not arrays..

like image 39
chayankQ Avatar answered Oct 02 '22 07:10

chayankQ


I solved this problem by using trim() function. the issue was with space.

so lets try

$unit_size = []; //please declare the variable type 
$unit_size = exolode("x", $unit_size);
$width  = trim ($unit_size[1] );
$height = trim ($unit_size[2] );

I hope this will help you.

like image 24
Jailendra Rajawat Avatar answered Oct 02 '22 08:10

Jailendra Rajawat


i think the only reason for this message is because target Array is actually an array like string etc (JSON -> {"host": "127.0.0.1"}) variable

like image 29
adnan ahmady Avatar answered Oct 02 '22 08:10

adnan ahmady


For PHP

//Setup Array like so
$memcachedConfig = array(
  "host" => "127.0.0.1",
  "port" => "11211"
);

//Always a good practice to check if empty

if(isset($memcachedConfig['host']) && isset($memcachedConfig['port'])){

    //Some codes

    print_r ($memcachedConfig['host']);
    print_r ($memcachedConfig['port']);

}

Just make sure to check that the value returning is not empty. So this example was for PHP so find out how to check if an array is empty in other languages.

like image 42
Delorme Grant Avatar answered Oct 02 '22 08:10

Delorme Grant


In my case: while fetching the database records in making sure to use result_array(); instead of row(); or row_array();

like image 39
codelone Avatar answered Oct 02 '22 09:10

codelone