- Output (echo/print) everything from a PHP Array
- 9 Answers 9
- Как вывести PHP массив
- Функция print_r()
- Результат:
- Функция var_dump()
- Результат:
- var_export()
- Результат:
- Цикл foreach
- Результат:
- Результат:
- Результат:
- Цикл for
- Результат:
- Цикл while
- Результат:
- Функция implode()
- Результат:
- How can I echo or print an array in PHP?
- print_r()
- var_dump()
- var_export()
- echo
Output (echo/print) everything from a PHP Array
Is it possible to echo or print the entire contents of an array without specifying which part of the array? The scenario: I am trying to echo everything from:
while($row = mysql_fetch_array($result))
9 Answers 9
If you want to format the output on your own, simply add another loop (foreach) to iterate through the contents of the current row:
while ($row = mysql_fetch_array($result)) < foreach ($row as $columnName =>$columnData) < echo 'Column name: ' . $columnName . ' Column data: ' . $columnData . '
'; > >
Or if you don’t care about the formatting, use the print_r function recommended in the previous answers.
while ($row = mysql_fetch_array($result)) < echo '
'; print_r ($row); echo ''; >
print_r() prints only the keys and values of the array, opposed to var_dump() whichs also prints the types of the data in the array, i.e. String, int, double, and so on. If you do care about the data types — use var_dump() over print_r().
For nice & readable results, use this:
function printVar($var) < echo '
'; var_dump($var); echo ''; >
The above function will preserve the original formatting, making it (more)readable in a web browser.
This function displays structured information about one or more expressions that includes its type and value. Arrays and objects are explored recursively with values indented to show structure.
I think you are looking for print_r which will print out the array as text. You can’t control the formatting though, it’s more for debugging. If you want cool formatting you’ll need to do it manually.
This is a little function I use all the time its handy if you are debugging arrays. Its pretty much the same thing Darryl and Karim posted. I just added a parameter title so you have some debug info as what array you are printing. it also checks if you have supplied it with a valid array and lets you know if you didn’t.
function print_array($title,$array)< if(is_array($array))< echo $title."
". "||---------------------------------||
". ""; print_r($array); echo "". "END ".$title."
". "||---------------------------------||
"; >else < echo $title." is not an array."; >>//your array $array = array('cat','dog','bird','mouse','fish','gerbil'); //usage print_array("PETS", $array);
PETS ||---------------------------------|| Array ( [0] => cat [1] => dog [2] => bird [3] => mouse [4] => fish [5] => gerbil ) END PETS ||---------------------------------||
Как вывести PHP массив
Примеры использования PHP функций и циклов для вывода всех элементов массива в окно браузера.
Функция print_r()
Функция print_r() выводит информацию о переменной в удобочитаемом виде. Чтобы отобразить пробелы и переносы результат функции нужно обернуть в тег .
$array = array( 'Andi', 'Benny', 'Cara', 'Danny', 'Emily', ); echo '
'; print_r($array); echo '';
Результат:
Array ( [0] => Andi [1] => Benny [2] => Cara [3] => Danny [4] => Emily )
Функция var_dump()
Функция var_dump() отображает информацию о переменной, включая тип и значение.
$array = array( 'Andi', 'Benny', 'Cara', 'Danny', 'Emily', ); echo '
'; var_dump($array); echo '';
Результат:
array(5) < [0]=>string(4) "Andi" [1]=> string(5) "Benny" [2]=> string(4) "Cara" [3]=> string(5) "Danny" [4]=> string(5) "Emily" >
var_export()
Функция var_export() возвращает строковое представление переменной в виде полноценного PHP-кода.
$array = array( 'Andi', 'Benny', 'Cara', 'Danny', 'Emily', ); echo '
'; echo var_export($array); echo '';
Результат:
array ( 0 => 'Andi', 1 => 'Benny', 2 => 'Cara', 3 => 'Danny', 4 => 'Emily', )
Цикл foreach
Цикл foreach специально создан для поэлементного перебора массивов.
$array = array( 'Andi', 'Benny', 'Cara', 'Danny', 'Emily', ); foreach ($array as $row) < echo $row . "
\r\n"; >Результат:
Andi
Benny
Cara
Danny
EmilyПример с выводом нумерованного списка с использованием индексов массива:
$array = array( 'Andi', 'Benny', 'Cara', 'Danny', 'Emily', ); foreach ($array as $n => $row) < echo ($n + 1) . '.' . $row . "
\r\n"; >Результат:
1.Andi
2.Benny
3.Cara
4.Danny
5.EmilyЧтобы не выводить последний
, добавим условие:$array = array( 'Andi', 'Benny', 'Cara', 'Danny', 'Emily', ); foreach ($array as $n => $row) < echo ($n + 1) . '.' . $row; if ($n < count($array) - 1) < echo "
\r\n"; > >Результат:
1.Andi
2.Benny
3.Cara
4.Danny
5.EmilyЦикл for
Цикл for подойдет только в случаях, когда индексы массива имеют непрерывную нумерацию.
$array = array( 'Andi', 'Benny', 'Cara', 'Danny', 'Emily', ); for ($n = 0; $n < count($array); $n++) < echo $n + 1 . '.' . $array[$n] . "
\r\n"; >Результат:
1.Andi
2.Benny
3.Cara
4.Danny
5.EmilyЦикл while
Цикл while такое же работает как и for .
$array = array( 'Andi', 'Benny', 'Cara', 'Danny', 'Emily', ); $index = 0; while ($index < count($array)) < echo $index + 1 . '.' . $array[$index] . "
\r\n"; $index++; >Результат:
1.Andi
2.Benny
3.Cara
4.Danny
5.EmilyФункция implode()
Также, для вывода массива удобно использовать функцию implode() , которая объединяет элементы массива через разделитель.
$array = array( 'Andi', 'Benny', 'Cara', 'Danny', 'Emily', ); echo implode("
\r\n", $array);Результат:
Andi
Benny
Cara
Danny
EmilyHow can I echo or print an array in PHP?
print_r($array); or if you want nicely formatted array then:
Nice and elegant. You might want to change the closing tag in #1 from
to.
@Robintag displays new lines and tabulation as it's outputed by print_r(); withoutyou would see a messy unformatted bounds of data. To see it formatted you should then view the html page source.foreach($results['data'] as $result) < echo $result['type'], '
'; >how can I insert this information in a database? for example, if I have a table with a column named type and i want o insert [0]['type'] , [1]['type'] and so on?
If you just want to know the content without a format (e.g., for debugging purposes) I use this:
This will show it as a JSON which is pretty human-readable.
I wanted to extract some data from a html - php document using Cordova InAppBrowser executeScript method, without json_encode($array) I could not achieve that! Thanks a lot @Mark E
There are multiple functions for printing array content that each has features.
print_r()
Prints human-readable information about a variable.
var_dump()
Displays structured information about expressions that includes its type and value.
array(3) < [0]=>string(1) "a" [1]=> string(1) "b" [2]=> string(1) "c" >
var_export()
Displays structured information about the given variable that returned representation is valid PHP code.
Note that because the browser condenses multiple whitespace characters (including newlines) to a single space (answer), you need to wrap above functions in to display result in thee correct format.
Also, there is another way to print array content with certain conditions.
echo
Output one or more strings. So if you want to print array content using echo , you need to loop through the array and in the loop use echo to print array items.
foreach ($arr as $key=>$item) < echo "$key =>$item
"; >