, , , , ,

How to traverse an array in PHP and print?

Posted by

Traverse Array in PHP

The most common task with arrays is to do something with every element—for instance, sending mail to each element of an array of addresses, updating each file in an array of filenames, or adding up each element of an array of prices. There are several ways to traverse arrays in PHP, and the one you choose will depend on your data values and the task you’re performing.

The foreach Construct
The most common way to loop over elements of an array is to use the foreach construct:

 $addresses = array('hack@pointpro.net', 'abroad@example.com'); 
   foreach ($addresses as $value) 
    echo "Processing $value\n<br />";  

Output:

Processing hack@pointpro.net
Processing abroad@example.com

PHP executes the body of the loop (the echo statement) once for each element of $addresses in turn, with $value set to the current element. Elements will be processed by their internal order. An alternative form of foreach gives you access to the current key:

$person = array('name' => 'Alex', 'age' => 35, 'wife' => 'Ally'); 
    foreach ($person as $k => $v) 
     echo "Alex's $k is $v\n<br />";

Output:

Alex’s name is Alex
Alex’s age is 35
Alex’s wife is Ally

In this case, the key for each element is placed in $k and the corresponding value is placed in $v. The foreach construct does not operate on the array itself, but rather on a copy of it.
You can insert or delete elements in the body of a foreach loop, safe in the knowledge that the loop won’t attempt to process the deleted or inserted elements.

guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x