How to Traverse an array in PHP and print?

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

Related Posts

PHP – strip_tags() Replace with Spaces Example

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…

Read More

How to Get Duplicate Values from Array in PHP?

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…

Read More

PHP explode() Function Example Tutorial

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…

Read More

How to Convert Array to String in PHP?

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…

Read More

How Can I Convert a String in PHP Into an Array?

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…

Read More

How to Use the array_merge() Function in PHP?

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…

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