Source: www.csrhymes.com

The PHP foreach loop

We think you might be interested in this job:

The PHP foreach loop | C.S. Rhymes C.S. Rhymes HomeBooksNigel's Intranet AdventureHow NOT to make a WebsiteHow NOT to use a SmartphoneMy WorkThemesPackagesSitesDemosStoriesSponsorsAboutBlogSponsorThe PHP foreach loopPHP FundamentalsPublished: Oct 9, 2021 by C.S. RhymesAn alternative to the for loop, the foreach loop is used to iterate or loop over an array. The foreach loop allows you to loop through the items in the array without setting a limit for it to stop like you do in a for loop.Once the foreach loop has looped through every item it will finish. If there are ten items in the array, then it will loop ten times.Basic Foreach LoopThe foreach loop accepts an array as the first argument and then you give a name for the individual array item.

The first argument is the array, then after the as you have a syntax that looks similar to the array syntax, as $key => $value where the first variable is the array key and the second is the array value.$trees=['oak'=>4,'ash'=>3,'birch'=>8,'maple'=>6,];foreach($treesas$tree=>$count){echo"There are $count$tree trees";echo'';}// There are 4 oak trees// There are 3 ash trees// There are 8 birch trees// There are 6 maple treesModifying the original valueIf you want to modify the values in an array you can use a foreach loop to do this by putting the & before the second argument.

Rather than having to use the index within the foreach loop, the tree name we can access the Tree’s properties (count and name) using the arrow syntax, such as $tree->count.$trees=[newTree('oak',4),newTree('ash',3)];foreach($treesas$tree){echo"There are $tree->count$tree->name trees";echo'';}There are lots of use cases for a foreach loop so hopefully this introduction will give you ideas to put the foreach loop to use in your code.PHPBeginnerCodeSharePlease enable JavaScript to view the comments powered by Disqus.Latest PostsThe PHP foreach loopAn alternative to the for loop, the foreach loop is used to iterate or loop over an array.
Newsletter

Get the latest Laravel/PHP jobs, events and curated articles straight to your inbox, once a week

Fathom Analytics | Fast, simple and privacy-focused website analytics. Fathom Analytics | Fast, simple and privacy-focused website analytics.
Community Partners