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.
$memcachedConfig
is not that array. Showvar_dump($memcachedConfig);
var_export($memcachedConfig)
just before the "print".