Print all the values of array

Как вывести 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
Emily

Источник

  • Different ways to write a PHP code
  • How to write comments in PHP ?
  • Introduction to Codeignitor (PHP)
  • How to echo HTML in PHP ?
  • Error handling in PHP
  • How to show All Errors in PHP ?
  • How to Start and Stop a Timer in PHP ?
  • How to create default function parameter in PHP?
  • How to check if mod_rewrite is enabled in PHP ?
  • Web Scraping in PHP Using Simple HTML DOM Parser
  • How to pass form variables from one page to other page in PHP ?
  • How to display logged in user information in PHP ?
  • How to find out where a function is defined using PHP ?
  • How to Get $_POST from multiple check-boxes ?
  • How to Secure hash and salt for PHP passwords ?
  • Program to Insert new item in array on any position in PHP
  • PHP append one array to another
  • How to delete an Element From an Array in PHP ?
  • How to print all the values of an array in PHP ?
  • How to perform Array Delete by Value Not Key in PHP ?
  • Removing Array Element and Re-Indexing in PHP
  • How to count all array elements in PHP ?
  • How to insert an item at the beginning of an array in PHP ?
  • PHP Check if two arrays contain same elements
  • Merge two arrays keeping original keys in PHP
  • PHP program to find the maximum and the minimum in array
  • How to check a key exists in an array in PHP ?
  • PHP | Second most frequent element in an array
  • Sort array of objects by object fields in PHP
  • PHP | Sort array of strings in natural and standard orders
  • How to pass PHP Variables by reference ?
  • How to format Phone Numbers in PHP ?
  • How to use php serialize() and unserialize() Function
  • Implementing callback in PHP
  • PHP | Merging two or more arrays using array_merge()
  • PHP program to print an arithmetic progression series using inbuilt functions
  • How to prevent SQL Injection in PHP ?
  • How to extract the user name from the email ID using PHP ?
  • How to count rows in MySQL table in PHP ?
  • How to parse a CSV File in PHP ?
  • How to generate simple random password from a given string using PHP ?
  • How to upload images in MySQL using PHP PDO ?
  • How to check foreach Loop Key Value in PHP ?
  • How to properly Format a Number With Leading Zeros in PHP ?
  • How to get a File Extension in PHP ?
  • How to get the current Date and Time in PHP ?
  • PHP program to change date format
  • How to convert DateTime to String using PHP ?
  • How to get Time Difference in Minutes in PHP ?
  • Return all dates between two dates in an array in PHP
  • Sort an array of dates in PHP
  • How to get the time of the last modification of the current page in PHP?
  • How to convert a Date into Timestamp using PHP ?
  • How to add 24 hours to a unix timestamp in php?
  • Sort a multidimensional array by date element in PHP
  • Convert timestamp to readable date/time in PHP
  • PHP | Number of week days between two dates
  • PHP | Converting string to Date and DateTime
  • How to get last day of a month from date in PHP ?
  • PHP | Change strings in an array to uppercase
  • How to convert first character of all the words uppercase using PHP ?
  • How to get the last character of a string in PHP ?
  • How to convert uppercase string to lowercase using PHP ?
  • How to extract Numbers From a String in PHP ?
  • How to replace String in PHP ?
  • How to Encrypt and Decrypt a PHP String ?
  • How to display string values within a table using PHP ?
  • How to write Multi-Line Strings in PHP ?
  • How to check if a String Contains a Substring in PHP ?
  • How to append a string in PHP ?
  • How to remove white spaces only beginning/end of a string using PHP ?
  • How to Remove Special Character from String in PHP ?
  • How to create a string by joining the array elements using PHP ?
  • How to prepend a string in PHP ?

Источник

How to print or echo all the values of an array in PHP?

We can print all the values of the array using a PHP foreach loop. The foreach loop iterates through each element within the array.

The foreach loop works on an array and objects only. We will get an error if we try to use the foreach loop with variables or other data types.

It is the easiest method to print all the array elements at once.

Example: Using foreach loop

In the given example, we have used the foreach loop to print all the elements of an array.

     "; foreach($fruits as $fruits)< echo $fruits . "
"; > ?>

Output

The array is:
Apple
Mango
Banana
Pears
Watermelon
Guava

Using print_r() function

We can also print all the values of the array using the print_r() function. This function is basically used to print the values in more human-readable form.

The print_r() function takes two arguments, the first parameter is the variable name whose value we want to print using this function. The second parameter is the return type which is optional and by default its value is false.

This function prints all the values of the array along with their index value.

Example: Using print_r() function

In the given example, we have used the print_r() function to print all the values of the array.

     

Output

Array ( [0] => Apple [1] => Mango [2] => Banana [3] => Pears [4] => Watermelon [5] => Guava )

Using var_dump() function

The var_dump() function is used to print all the values of the array at once. The function prints the value of the array along with its index value, data type, and length.

This function takes the single parameter which can be the name of the variable whose value we want to print.

Example: Using var_dump() function

In this example, we have used the var_dump() function to print all the values of an array. This method also prints the length, index value, and the datatype of the value.

     

Output

array(6) < [0]=>string(5) «Apple» [1]=> string(5) «Mango» [2]=> string(6) «Banana» [3]=> string(5) «Pears» [4]=> string(10) «Watermelon» [5]=> string(5) «Guava» >

Conclusion

In this lesson, we have learned how to print all the values of an array in PHP. There are several methods and pre-defined functions that enable us to print all the values of the array at once. Here, we have discussed three methods with the help of them we can print all the values of an array, these methods are:

Источник

Читайте также:  Html document create element
Оцените статью