Skip to content
Related Articles

Related Articles

How to print all the values of an array in PHP ?
  • Last Updated : 01 Jun, 2020

We have given an array containing some array elements and the task is to print all the values of an array arr in PHP. In order to do this task, we have the following approaches in PHP:

Approach 1: Using foreach loop: The foreach loop is used to iterate the array elements. The foreach loop though iterates over an array of elements, the execution is simplified and finishes the loop.

Syntax:

foreach( $array as $element ) {
    // PHP Code to be executed
}

Example:

PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// PHP program to print all 
// the values of an array
    
// given array
$array = array("Geek1", "Geek2",
           "Geek3", "1", "2","3");  
  
// Loop through array
foreach($array as $item){
    echo $item . "\n";
}
  
?>

chevron_right


Output



Geek1
Geek2
Geek3
1
2
3
 

Approach 2: Using count() function and for loop: The count() function is used to count the number of element in an array and for loop is used to iterate over the array.

Syntax:

for (initialization; test condition; increment/decrement) {
    // Code to be executed
}

Example:

PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// PHP program to print all 
// the values of an array
    
// given array
$array = array("Geek1", "Geek2",
            "Geek3", "1", "2","3");  
  
$items = count($array);
  
// Loop through array
for($num = 0; $num < $items; $num += 1){
    echo  $array[$num]. "\n";
}
  
?>

chevron_right


Output

Geek1
Geek2
Geek3
1
2
3
 
My Personal Notes arrow_drop_up
Recommended Articles
Page :