In the previous exercise, Solved tasks for PHP lessons 7-11, we've practiced our knowledge from previous lessons.

Bạn đang xem: Lesson 12, php foreach

In the previous lesson, Solved tasks for PHP lessons 7-11, we went over how khổng lồ use forand while loops in PHP. In today"s lesson, we"re going to finish upwith loops & show you how to lớn use them properly when working with arrays.

Filling an array using loops

Loops are widely used for automatizing array manipulations. Usually, thereare lots of items in an array và dealing with them one by one would certainlynot be a good idea. Let"s start by filling an array with numbers from1 lớn 100.

We know the number of loop iterations, 100, so we will use thefor loop. Its control variable ($i) will go from0 to lớn 99 (an array of 100 items will haveindexes from 0 - 99). We"ll have to increase the valueby 1 because we want values from 1 to100:

$numbers = array();for ($i = 0; $i 100; $i++) $numbers<$i> = $i + 1;

Printing an array using loops

We now have an array filled with 100 numbers. However, we don"t usuallygenerate arrays lượt thích this. In most cases, we retrieve values from databases.Regardless, the approach shown above will bởi vì for now
Another common thing to vì chưng isprint values from an array into a table.

The for loop

I"m pretty sure you could have come up with the following code at this pointif you were given the task:

PHP$numbers = array();for ($i = 0; $i 100; $i++) $numbers<$i> = $i + 1;echo("

");for ($i = 0; $i 100; $i++) echo("");echo("
" . Htmlspecialchars($numbers<$i>) . "
");/PHPThe code prints the contents of the array into a table using thefor loop. In real applications, there would most likely be otherkinds of nội dung in the array such as comments from a database, which we willget to soon enough.

The foreach loop

As a matter of fact, there is a shorter & more sophisticated way lớn printarrays, the foreach loop. Its usage is as follows:

foreach ($collection as $element)Foreach iterates over array items & stores the current thành tựu ina variable. This is the difference between foreach andfor loops, which store the item"s index, not the thành tựu itself.

Here"s how we would print the array into a table usingforeach:

PHP$numbers = array();for ($i = 0; $i 100; $i++) $numbers<$i> = $i + 1;echo("

");foreach($numbers as $number) echo("");echo("
" . Htmlspecialchars($number) . "
");/PHPThe program"s output will be identical. Foreach is mostly usedfor reading và working with objects, which we will get to later as well becauseit is way more readable than for loops.

The loop"s variable in the example above contains a copy of the element at agiven position. If we tried to modify the variable $number, itwouldn"t affect the array at all because all we"d be doing is modifying a copyof the current element và not the element itself. On the other hand, if wewanted khổng lồ multiply every single element by 2, using a for loop berelatively easier:

for ($i = 0; $i 100; $i++) $numbers<$i> = $numbers<$i> * 2;Either way, we don"t want to lớn modify the original array, so we"ll useforeach for these intents và purposes.

PHP array functions

PHP provides a wide range of functions for working with arrays. We won"t gointo them in detail, we"ll just show you a các mục of the most important ones. Eachfunction references the corresponding page in the official PHP manual where itis described và shown in examples. Every time we program something in PHP, it"sa good idea to check whether a function for what we need already exists. Doingso will save us time và prevent us from making mistakes. Internal PHP functionsare written in the C language, so they"re way faster than anything we could comeup with.

You don"t absolutely have to lớn examine these functions in detail, just readwhat they do và look them up later when you need them.

array_fillFills an array with values
array_flipExchanges all keys with their values.
array_intersec­t_keyComputes array intersections using keys for comparison.
array_intersectComputes array intersections.
array_keysReturns all of the keys or a subset of the keys in a given array.
array_mapApplies a callback lớn the elements of a given array.

Xem thêm: Combo Sách: Khơi Dậy Cảm Hứng Học Tập + Bí Quyết Học Tập Toàn Diện ”

array_mergeMerges one or more arrays.
array_popPops the element off the end of an array.
array_pushPushes one or more elements onto the over of an array.
array_reverseReturns an array with its elements ordered backward.
array_searchSearches the array for a given value & returns the corresponding key ifsuccessful.
array_shiftShifts an element off the beginning of an array.
array_sumCalculates the sum of values in an array.
array_uniqueRemoves duplicate values from an array.
array_unshiftPrepends one or more elements to the beginning of an array.
array_valuesReturns all the values of an array.
countCounts all elements in an array or things in an object.
extractEstablishes a variable for each array key and assigns the correspondingvalue khổng lồ it.
ksortSorts an array by keys.
sortSorts an array by values.

Array of arrays

Have you ever wondered whether we could put an entire array into another?Arrays are an ordinary data type, so we can absolutely insert arrays one intoanother. We"ll work with arrays like these very often:

$paul = array( "name" => "Paul Smith", "age" => "20",);$thomas = array( "name" => "Thomas Doe", "age" => "50",);$jane = array( "name" => "Jane Doe", "age" => "35",);$people = array($paul, $thomas, $jane);We created 3 arrays and stored them into another at the very end. The firstcouple of arrays represent people, the outer array keeps them together so we canwork with them easily.

The same exact array would be returned by a database request for users.Except the first and last names would probably be separate values. With all thatyou know, you should be able to lớn print it out without any help. Just lớn be sure,we"ll vày it together:

PHP$paul = array( "name" => "Paul Smith", "age" => "20",);$thomas = array( "name" => "Thomas Doe", "age" => "50",);$jane = array( "name" => "Jane Doe", "age" => "35",);$people = array($paul, $thomas, $jane);echo("

");echo("NameAge");foreach ($people as $person) echo(""); echo("");echo("
" . Htmlspecialchars($person<"name">) . "" . Htmlspecialchars($person<"age">) . "