Thursday, October 16, 2025
HomeLanguagesHow to print all the values of an array in PHP ?

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

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




<?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";
}
  
?>


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




<?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";
}
  
?>


Output

Geek1
Geek2
Geek3
1
2
3
 
RELATED ARTICLES

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11954 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS