Wednesday, July 3, 2024
HomeLanguagesPhpHow 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
 

Nicole Veronica Rubhabha
Nicole Veronica Rubhabha
A highly competent and organized individual DotNet developer with a track record of architecting and developing web client-server applications. Recognized as a personable, dedicated performer who demonstrates innovation, communication, and teamwork to ensure quality and timely project completion. Expertise in C#, ASP.Net, MVC, LINQ, EF 6, Web Services, SQL Server, MySql, Web development,
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments