Массив и foreach

$posts = array( "message" => 'this is a test message' ); foreach ($posts as $post) { echo $post['message']; } 

Почему приведенный выше код выводит только первую букву в сообщении? «Т».

Благодаря!

Solutions Collecting From Web of "Массив и foreach"

foreach принимает каждый элемент массива и присваивает его переменной. Чтобы получить результаты, я предполагаю, что вы ожидаете, что вам просто нужно сделать:

 foreach ($posts as $post) { echo $post; } 

Специфика относительно того, почему ваш код не работал: $post будет содержимым элемента массива – в этом случае строка. Поскольку PHP не сильно набирает / поддерживает жонглирование типа, вы можете на самом деле работать со строкой, как если бы это был массив, и добираться до каждого символа в последовательности:

 foreach ($posts as $post) { echo $post[0]; //'t' echo $post[1]; //'h' } 

Очевидно, что $post['message'] не является допустимым элементом, и нет явного преобразования из (string)'message' в int , поэтому это вычисляется до $post[0] .

 # $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, ie # ((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']; } 

Возможно, вы хотите:

 $posts = array( array( "message" => 'this is a test message' ) ); foreach ($posts as $post) { echo $post['message']; } 

Или это:

 $posts = array( "message" => 'this is a test message' ); foreach ($posts as $key => $post) { # $key === 'message' echo $post; } 

Я бы добавил к ответу iAn что-то: если вы хотите каким-то образом получить доступ к ключу значения, используйте это:

 foreach ($posts as $key => $post) { echo $key . '=' . $post; } 

Результат:

 message=this is a test message