Thursday, September 4, 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
32264 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6632 POSTS0 COMMENTS
Nicole Veronica
11800 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11860 POSTS0 COMMENTS
Shaida Kate Naidoo
6749 POSTS0 COMMENTS
Ted Musemwa
7025 POSTS0 COMMENTS
Thapelo Manthata
6698 POSTS0 COMMENTS
Umr Jansen
6718 POSTS0 COMMENTS