Advertencia de desplazamiento de cadena ilegal PHP
Recibo un extraño error de PHP después de actualizar mi versión de php a 5.4.0-3.
Tengo esta matriz:
Array
(
[host] => 127.0.0.1
[port] => 11211
)
Cuando intento acceder a él de esta manera recibo advertencias extrañas
print $memcachedConfig['host'];
print $memcachedConfig['port'];
Warning: Illegal string offset 'host' in ....
Warning: Illegal string offset 'port' in ...
Realmente no quiero simplemente editar mi php.ini y vuelva a establecer el nivel de error.
12 answers
Por favor, inténtelo de esta manera.... He probado este código.... Funciona....
$memcachedConfig = array("host" => "127.0.0.1","port" => "11211");
print_r ($memcachedConfig['host']);
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-06-28 11:41:12
El error Illegal string offset 'whatever' in...
generalmente significa: estás tratando de usar una cadena como una matriz completa.
Eso es realmente posible ya que las cadenas pueden ser tratadas como matrices de caracteres individuales en php. Así que estás pensando que var var es una matriz con una clave, pero es solo una cadena con claves numéricas estándar, por ejemplo:
$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
Puedes ver esto en acción aquí: http://ideone.com/fMhmkR
Para aquellos que llegan a esta pregunta tratando de traducir la vaguedad de el error en algo que hacer al respecto, como yo estaba.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-08-20 16:55:15
TL;DR
Estás tratando de acceder a un string
como si fuera un array, con una clave que es un string
. string
no entenderán eso. En el código podemos ver el problema:
"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.
En profundidad
Veamos ese error: {[32]]}
Advertencia: Desplazamiento de cadena ilegal 'port' in...
Advertencia: Desplazamiento de cadena ilegal 'port' in...
, ¿Qué dice? Dice que estamos tratando de usar la cadena 'port'
como un desplazamiento para una cadena. Así:
$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 ...
¿Qué causa esto?
Para algunos razón por la que esperabas un array
, pero tienes un string
. Sólo una confusión. Tal vez su variable fue cambiada, tal vez nunca fue un array
, realmente no es importante.
¿Qué se puede hacer?
Si sabemos que deberíamos tener un array
, deberíamos hacer un poco de depuración básica para determinar por qué no tenemos un array
. Si no sabemos si tendremos un array
o string
, las cosas se vuelven un poco más complicadas.
Lo que podemos hacer es todo tipo de comprobaciones para asegurarnos de que no tenemos avisos, advertencias o errores con cosas como is_array
y isset
o 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
}
Hay algunas diferencias sutiles entre isset
y array_key_exists
. Por ejemplo, si el valor de $array['key']
es null
, isset
devuelve false
. array_key_exists
simplemente comprobará que, bueno, la clave existe.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-01-15 09:03:54
Hay muchas respuestas excelentes aquí, pero encontré que mi problema era un poco más simple.
Estaba intentando ejecutar el siguiente comando:
$x['name'] = $j['name'];
Y estaba recibiendo este error illegal string
en $x['name']
porque no había definido la matriz primero. Así que puse la siguiente línea de código antes de intentar asignar cosas a $x[]
:
$x = array();
Y funcionó.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-10 21:08:48
A partir de PHP 5.4 necesitamos pasar el mismo valor de tipo de datos que una función espera. Por ejemplo:
function testimonial($id); // This function expects $id as an integer
Al invocar esta función, si se proporciona un valor de cadena como este:
$id = $array['id']; // $id is of string type
testimonial($id); // illegal offset warning
Esto generará una advertencia de desplazamiento ilegal debido al desajuste de los tipos de datos. Para resolver esto, puede usar settype
:
$id = settype($array['id'],"integer"); // $id now contains an integer instead of a string
testimonial($id); // now running smoothly
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-11 16:51:33
Un poco tarde para la pregunta, pero para otros que están buscando: Obtuve este error al inicializar con un valor (tipo) incorrecto:
$varName = '';
$varName["x"] = "test"; // causes: Illegal string offset
El camino correcto es:
$varName = array();
$varName["x"] = "test"; // works
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-01-03 15:08:07
Antes de comprobar la matriz, haga esto:
if(!is_array($memcachedConfig))
$memcachedConfig = array();
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-12-04 11:14:47
En mi caso, cambio mysql_fetch_assoc a mysql_fetch_array y resuelvo. Se tarda 3 días en resolver : - (y las otras versiones de mi proyecto se ejecutan con fetch assoc.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-05 18:56:52
Solo en caso de que ayude a alguien, estaba recibiendo este error porque me olvidé de unserialize una matriz serializada. Eso es definitivamente algo que verificaría si se aplica a su caso.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-07 09:52:51
Es una vieja pero en caso de que alguien pueda beneficiarse de esto. También obtendrá este error si su matriz está vacía.
En mi caso tuve:
$buyers_array = array();
$buyers_array = tep_get_buyers_info($this_buyer_id); // returns an array
...
echo $buyers_array['firstname'] . ' ' . $buyers_array['lastname'];
Que cambié a:
$buyers_array = array();
$buyers_array = tep_get_buyers_info($this_buyer_id); // returns an array
...
if(is_array($buyers_array)) {
echo $buyers_array['firstname'] . ' ' . $buyers_array['lastname'];
} else {
echo 'Buyers id ' . $this_buyer_id . ' not found';
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-09 17:58:20
En mi caso, lo resolví cuando cambié en la función que hace consulta sql
después de: return json_encode($array)
entonces: return $array
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-06-09 07:21:58
Funciona para mí:
Código de prueba mío:
$var2['data'] = array ('a'=>'21','b'=>'32','c'=>'55','d'=>'66','e'=>'77');
foreach($var2 as $result)
{
$test = $result['c'];
}
print_r($test);
Salida: 55
Compruébalo chicos. Gracias
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-10-01 19:44:15