How to print all the values of an array in PHP ? (original) (raw)

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:

Table of Content

**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( arrayasarray as arrayaselement ) {
// PHP Code to be executed
}

**Example:

PHP `

`

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 `

items=count(items = count(items=count(array); // Loop through array for($num = 0; num<num < num<items; $num += 1){ echo array[array[array[num]. "\n"; } ?>

`

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:

PHP `

`

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.

PHP `

`

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

PHP `

`

Output

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