each() - 返回数组中当前的键/值对并将数组指针向前移动一步 - php 数组函数
each()
(PHP 4, PHP 5, PHP 7)
返回数组中当前的键/值对并将数组指针向前移动一步
WarningThis function has beenDEPRECATEDas of PHP 7.2.0. Relying on this functionis highly discouraged.
说明
each(array &$array): array返回数组中当前的键/值对并将数组指针向前移动一步
在执行each()之后,数组指针将停留在数组中的下一个单元或者当碰到数组结尾时停留在最后一个单元。如果要再用 each 遍历数组,必须使用reset()。
参数
$array输入的数组。
返回值
返回$array数组中当前指针位置的键/值对并向前移动数组指针。键值对被返回为四个单元的数组,键名为0,1,key和value。单元0和key包含有数组单元的键名,1和value包含有数据。
如果内部指针越过了数组的末端,则each()返回FALSE
。
范例
Example #1each()例子
$bar现在包含有如下的键/值对:
Array ( [1] => bob [value] => bob [0] => 0 [key] => 0 )
$bar现在包含有如下的键/值对:
Array ( [1] => Bob [value] => Bob [0] => Robert [key] => Robert )
each()经常和list()结合使用来遍历数组,例如:
用each()遍历数组
以上例程会输出:
a => apple b => banana c => cranberryCaution
因为将一个数组赋值给另一个数组时会重置原来的数组指针,因此在上边的例子中如果我们在循环内部将$fruit赋给了另一个变量的话将会导致无限循环。
Warningeach()will also accept objects, but may return unexpected results. Its therefore not recommended to iterate though object properties witheach().
参见
key()
从关联数组中取得键名list()
把数组中的值赋给一组变量current()
返回数组中的当前单元reset()
将数组的内部指针指向第一个单元next()
将数组中的内部指针向前移动一位prev()
将数组的内部指针倒回一位- foreach
- Object Iteration
Regarding speed of foreach vs while(list) =each I wrote a benchmark script and the results are that clearly foreach is faster. MUCH faster. Even with huge arrays (especially with huge arrays). I tested with sizes 100,000. 1,000,000 and 10,000,000. To do the test with 10 million i had to set my memory limit real high, it was close to 1gb by the time it actually worked. Anyways, here are some of my results: with 1,000,000 time for foreach = 0.0244591236115. time list each = 0.158002853394. desktop:/media/sda5/mpwolfe/tests$ php test.php time for foreach = 0.0245339870453. time list each = 0.154260158539. desktop:/media/sda5/mpwolfe/tests$ php test.php time for foreach = 0.0269000530243. time list each = 0.157305955887. then with 10,000,000: desktop:/media/sda5/mpwolfe/tests$ php test.php time for foreach = 1.96586894989. time list each = 14.1371650696. desktop:/media/sda5/mpwolfe/tests$ php test.php time for foreach = 2.02504014969. time list each = 13.7696218491. desktop:/media/sda5/mpwolfe/tests$ php test.php time for foreach = 2.0246758461. time list each = 13.8425710201. by the way, these results are with php 5.2 i believe, and a linux machine with 3gb of ram and 2.8ghz dual core pentium
It's worth noting that references to an array don't have thier own array pointer, and taking a reference to an array doesn't reset it's array pointer, so this works as you would expect it would by eaching the first three items of the array, rather than the first item 3 times.
Use foreach instead of while, list and each. Foreach is: - easier to read - faster - not influenced by the array pointer, so it does not need reset(). It works like this:
An odd function to deprecate. If you're keeping track of an array pointer in a collection outside a foreach loop you don't care about performance and the utility of this function is core. Instead you must call two functions: current() and then next() to replicate its behaviour.
If you want to display the hole structure (tree) of your array, then you can use this recursive solution.
To panania at 3ringwebs dot com: If you know for certain that you are only receiving one row, the while becomes redundant. To shorten your code: $strSQL = "SELECT * FROM table WHERE id=1"; $RecordsetSelect = $db->runQuery ($strSQL); list($key, $val) = mysql_fetch_row($RecordsetSelect); echo "$key => $val\n"; mysql_free_result($RecordsetSelect); With only one row being returned this is more elegant a solution, but just being nit-picky in essence. It also shows another quick way of using list.
If you forget to reset the array before each(), the same code may give different results with different php versions. In PHP 5.2.0: 2 4 6 In PHP 5.2.6: 4 6
If you want to iterate over a two-dimensional, sparse array, and want to first display every first element, then every second and so on, you can use this code: $fruits = array ( "fruits" => array ( "a" => "orange", "b" => "banana", "c" => "apple" ), "numbers" => array ( 1, 2, 3, 4, 5, 6 ), "holes" => array ( "first", 5 => "second", "third", 10 => "fourth", ) ); $done = False; while ($done == False) { $done = True; // Important: &$val has to be a reference (use the &), // if you don't, the internal counter of $val will be // re-initialized each time and you loop over the first elements // for eternity. foreach($fruits as $key => &$val) { if (list($inner_key, $inner_val) = each(&$val)) { $done = False; echo "$key : : $inner_key => $inner_val
\n"; } } } NOTE: this is just a quick hack, if you know a better way, post it!
I wrote a short and pretty simple script to search through associative arrays for some value in the values, heres a simplifyed example of it: will output: Searching the array foo for rich: A match was not found in bob A match was found in bill A match was not found in barbie
I've found a compact way to cycle through an associative array using for statement (not while, as it has been done in the most of examples below): or You hardly forget to add reset($array) code line using such construction.
Rector has an automated fix ('ListEachRector') to migrate away from `each()`: https://github.com/rectorphp/rector/blob/master/docs/AllRectorsOverview.md#listeachrector If you look at the code example you'll see this is even quite simple to do by hand.
each was deprecated because it exposed too much of the internal implementation details, blocking language development. ("We can't do X because it would break each().") https://wiki.php.net/rfc/deprecations_php_7_2#each If you want an array pointer, maintain it yourself. Probably a good idea anyway, because then it's visible in the code.
This function will help you dump any variable into XML structure. //dump var into simple XML structure function var_dump_xml($tagname,$variable,$level=0) { for($i=0;$i0) { echo $marg."".htmlspecialchars($variable)."\n"; }; }; /* example: $myVar = array("name"=>"Joe", "age"=>"26", "children"=>array("Ann","Michael")); var_dump_xml("myVarTag",$myVar); */
I usually work a lot with 2D arrays. Since I've had some trouble traversing them correctly maybe someone out there also experienced those problems and can use this one. It's based on a 2D-array called $array[$x][$y]. At some (but not necessarily all) (x,y) there is a value I want to reach. Note that I do not know beforehand the ranges of $x or $y (that is their highest and lowest values). while (list ($x, $tmp) = each ($array)) { while (list ($y, $val) = each ($tmp)) { echo "$x, $y, $val"; } } The answer for each (x,y) pair can thus be (providng, of course those values where in your array beforehand): 1, 1, 2 2, 2, 0 3, 1, 1 5, 2, 2 5, 1, 2 Note that only the (x,y) pairs with a corresponding value is shown. Hang in there Jon Egil Strand NTNU
Be sure to use the integrated functions "unset();" or "reset();" - many people forget this and wonder about the created output!
I wanted to be able to add to an array while looping through it. foreach does not allow this because it is using a secret copy of the array. each makes this possible (tested on PHP 4).
In PHP 7.2 we can use foreach() to replace each(), such as: foreach($array as $key => $value) { //do something }
Ok Here's one for iterating multidimensional array .. using foreach
Remember to use "reset()" if you iterate over an array with "each()" more than once! Example: while(list($key,$value) = each($array)){ // code here } NOW the internal pointer on $array is at the end of the array, and another attempt at an iteration like the one above will result in zero executions of the code within the "while" block. You MUST call "reset($array)" to reset the internal array pointer before iterating over the array again from the first element.
/* Iterating using objects via each */ class SAI { public function __toString() { return __CLASS__; } } $a = new SAI(); $b = new SAI(); $c = new SAI(); $d = new SAI(); $e = new SAI(); $objarray = array($a,$b,$c,$d,$e); reset($objarray); while (list($key, $val) = each($objarray)) { echo "$key => $val\n"; } //Results 0 => SAI 1 => SAI 2 => SAI 3 => SAI 4 => SAI Warning: each() will also accept objects, but may return unexpected results. It's therefore not recommended to iterate though object properties with each().
The following example is invalid in PHP 7 : The correct writing is This is because the "list ()" command on the left no longer works in PHP 7 and there is no replacement command. Which is very deplorable because this command was strongly used and allowed in a simple way to assign variables from array.
鹏仔微信 15129739599 鹏仔QQ344225443 鹏仔前端 pjxi.com 共享博客 sharedbk.com
图片声明:本站部分配图来自网络。本站只作为美观性配图使用,无任何非法侵犯第三方意图,一切解释权归图片著作权方,本站不承担任何责任。如有恶意碰瓷者,必当奉陪到底严惩不贷!