# $posts is an array with one index ('message')
$posts = array(
"message" => 'this is a test message'
);
# You iterate over the $posts array, so $post contains
# the string 'this is a test message'
foreach ($posts as $post) {
# You try to access an index in the string.
# Background info #1:
# You can access each character in a string using brackets, just
# like with arrays, so $post[0] === 't', $post[1] === 'e', etc.
# Background info #2:
# You need a numeric index when accessing the characters of a string.
# Background info #3:
# If PHP expects an integer, but finds a string, it tries to convert
# it. Unfortunately, string conversion in PHP is very strange.
# A string that does not start with a number is converted to 0, i.e.
# ((int) '23 monkeys') === 23, ((int) 'asd') === 0,
# ((int) 'strike force 1') === 0
# This means, you are accessing the character at position ((int) 'message'),
# which is the first character in the string
echo $post['message'];
}
Qu'est-ce que vous voulez peut-être est soit ceci:
$posts = array(
array(
"message" => 'this is a test message'
)
);
foreach ($posts as $post) {
echo $post['message'];
}
Ou ceci:
$posts = array(
"message" => 'this is a test message'
);
foreach ($posts as $key => $post) {
# $key === 'message'
echo $post;
}
Je suis vraiment surpris qu'il imprime quoi que ce soit du tout ... Vous ne devriez pas pouvoir indexer dans une chaîne en utilisant un paramètre associatif (ie. une chaîne) ... Je dirais que c'est probablement un comportement indéfini au mieux. –
@Matthew: L'explication de cela est dans ma réponse. – soulmerge