How to Traverse an array in PHP and print?

Posted by

Upgrade & Secure Your Future with DevOps, SRE, DevSecOps, MLOps!

We spend hours scrolling social media and waste money on things we forget, but won’t spend 30 minutes a day earning certifications that can change our lives.
Master in DevOps, SRE, DevSecOps & MLOps by DevOps School!

Learn from Guru Rajesh Kumar and double your salary in just one year.


Get Started Now!

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:-

Leave a Reply

Your email address will not be published. Required fields are marked *

0
Would love your thoughts, please comment.x
()
x