VOOZH about

URL: https://www.geeksforgeeks.org/php/how-to-print-all-the-values-of-an-array-in-php/

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


  • Courses
  • Tutorials
  • Interview Prep

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

Last Updated : 15 Jul, 2024

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 for-each loop:

The foreach loop is used to iterate the array elements. For each 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:


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:


Output
Geek1
Geek2
Geek3
1
2
3
 

Approach 3: Using implode():

The implode() function in PHP joins array elements into a single string using a specified separator. It’s useful for creating a readable list of array values

Example:


Output
apple, banana, cherry

Approach 4: Using print_r() Function

The print_r() function in PHP outputs a human-readable representation of any variable. When used with arrays, it prints the entire array structure, making it easy to see both keys and values.

Example: In this example, the print_r() function is used to print all the values of the given array. The output includes the indices and the corresponding values in a readable format, making it easy to understand the structure and contents of the array.


Output
Array
(
 [0] => apple
 [1] => banana
 [2] => cherry
 [3] => date
)

Using var_dump() Function

The var_dump() function in PHP displays detailed information about a variable, including its type and value. When used with an array, it outputs each element with its index and value, making it useful for debugging and understanding the structure of complex arrays.

Example


Output
array(3) {
 [0]=>
 string(5) "apple"
 [1]=>
 string(6) "banana"
 [2]=>
 string(6) "cherry"
}


Comment