How to Traverse an array in PHP and print?

Posted by

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 and the task you’re performing.

Example:-

<!DOCTYPE html>
<html>
	<body>
        <?php
            $array = array("Lux","Sampoo");

            foreach($array as $value) {
              print  " $value";
            }
        ?>
	</body>
</html>

Output:-

Lux Shampoo

Example:-

<!DOCTYPE html>
<html>
	<body>
        <?php
            $fnames = ["Amit", "Rahul", "Vijay", "Ravi", "Roshan"];

            $arrObject = new ArrayObject($fnames);
            $arrayIterator = $arrObject->getIterator();
                    
            while( $arrayIterator->valid() ){
                echo $arrayIterator->current() . "<br />";
                $arrayIterator->next();
            }
        ?>
	</body>
</html>

Output:-

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x