print_r() function is used to print an array in PHP. In the parameter of print_r() function pass array which you want to be printed.
1. Print an array 2. Print values by indexing number 3. Print array's all value by loop |
If you are trying to print an array by using echo
then definitely you are getting a notice - Array to string conversion in C:\ path
Print array in PHP
<?php
$data = ["Apple","Samsung","Xiaomi","Realme","Oppo","Vivo"];
print_r($data);
?>
Output=> Array ( [0] => Apple [1] => Samsung [2] => Xiaomi [3] => Realme [4] => Oppo [5] => Vivo )
Print data from an array by indexing number in PHP
The indexing number of an array starts from 0. Therefore, To print the first value of array, the indexing number will be 0, for the second value, the indexing number will be 1, etc.
Indexing number is passed just after an array name in the big bracket - [ ].
When I want to print Apple then I will use $data[0]. This is a single value of an array so you can print it by echo also. See below code example~
<?php
$data = ["Apple","Samsung","Xiaomi","Realme","Oppo","Vivo"];
echo $data[0];
?>
Or print array's single value by print_r()
<?php
$data = ["Apple","Samsung","Xiaomi","Realme","Oppo","Vivo"];
print_r($data[2]);
?>
Print all values of the array in PHP by loop
you need to run a loop to print all the values of an array.
First, we need to calculate the length of the array for a loop. You can do it easily by using either sizeOf() function or count() function of PHP.
<?php
$data = ["Apple","Samsung","Xiaomi","Realme","Oppo","Vivo"];
$length = count($data);
for($i=0;$i<$length;$i++)
{
$array_val = $data[$i];
echo $array_val."<br>";
}
?>
The output of the above code:-
In the above example, I used <br>
tag for the line breaking while printing the data. We use a dot (.) to concatenate two types of data in Php.
The first time $i
value will be 0, so Apple will be printed and the line will be broken by <br>
tag.
The second time $i
value will be 1, so Samsung will be printed. and so on till $i<$length
.
Publish A Comment