PHP Print all values of an Array

PHP array is efficient way to store large number of data in to a variable name. Situation may come, where we may want to print all the values of array.

Print all values of an Array

To print an array, we must have to know the total number of values in the array.

If you are not aware of what is array, how arrays are declared, then read: PHP Arrays

Example:

Lets create an array which contains five different fruit names.

<?php

$fruits=array(“Banana”,”Apple”,”Grape”,”Jackfruit”,”Papaya”);

?>

To print all the values the array variable $fruits, we can do it following way.

<?php

$fruits=array(“Banana”,”Apple”,”Grape”,”Jackfruit”,”Papaya”);

echo $fruits[0];

echo $fruits[1];

echo $fruits[2];

echo $fruits[3];

echo $fruits[4];

?>

The above code would print all the fruit names.

But such approach has demerit. Because here we are aware of total number of values present in the array and that is 5.

What if the array has contained 1000 of values?

For such scenario loop would be beneficial to execute the values in loop.

If you are not aware of for loop, then read: PHP – For Loop

If you are not aware of while loop, then read: PHP- While Loop

Print values of an array using while loop:

Using while loop we can print all the values of an array. For this we are going to use count function of php, to get total number of values in an array

<?php

$fruits=array(“Banana”,”Apple”,”Grape”,”Jackfruit”,”Papaya”);

$i=0;

while($i<count($fruits)){

echo $fruits[$i];

$i++;

}

?>

The above code would print all the fruit names.

Print values of an array using for loop:

Using for loop, we can also print all the values of an array. For this, we are going to use count function of php, to get total number of values in an array.

<?php

$fruits=array(“Banana”,”Apple”,”Grape”,”Jackfruit”,”Papaya”);

for($i=0;$i<count($fruits);$i++){

echo $fruits[$i];

}

?>

The above code would print all the values of the array.

Print values of an array using foreach loop:

Alternatively, PHP is providing foreach loop using which we can also print all the values of an array. For this we dont require total number of values of the array.

<?php

$fruits=array(“Banana”,”Apple”,”Grape”,”Jackfruit”,”Papaya”);

foreach($fruits as $fruit){

echo $fruit;

}

?>

The above code would print all the values of the array.

In foreach loop, we have used $fruits as $fruit.

What it does?

It is referring each value in the array.

Instead of we could use any name, that we want to refer to each element of an array.

foreach($fruits as $elephant){

echo $elephant;

}

The above code would too print each fruit name.

Foreach loop saves time and effort.

Try all three four ways to fetch all the values from an array. Follow which ever approach appears ease to you to fetch values from an array.