note 89009 added to control-structures.foreach
| From: | peter dot swietoslawski at gmail dot com | Date: | Wed, 18 Feb 2009 11:03:14 +0000 |
| Subject: | note 89009 added to control-structures.foreach | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-150779@lists.php.net to get a copy of this message | ||
It should be pointed out in documentation that iterating with foreach on nonlinear
(numerically-indexed) like:
<?php
$my_arr = array();
$my_arr[3] = 'chestnut';
$my_arr[1] = 'apple';
$my_arr[2] = 'banana';
?>
or assoc arrays with non-alphabetically ordered keys like:
<?php
$my_arr = array();
$my_arr['c'] = 'chestnut';
$my_arr['a'] = 'apple';
$my_arr['b'] = 'banana';
?>
will pull array values by the order of elements creation not by their indexes/keys alphabetical
order as expected.
<?php
foreach ($my_arr as $key => $val) {
echo 'key: '.$key.' val: '.$val.'<br />';
}
?>
Will produce appropriately:
key: 3 val: chestnut
key: 1 val: apple
key: 2 val: banana
key: c val: chestnut
key: a val: apple
key: b val: banana
To iterate through above arrays you need to sort them first by index/keys using ksort().
----
Server IP: 193.95.141.37
Probable Submitter: 86.47.50.146
----
Manual Page -- http://www.php.net/manual/en/control-structures.foreach.php
Edit -- https://master.php.net/note/edit/89009
Del: integrated -- https://master.php.net/note/delete/89009/integrated
Del: useless -- https://master.php.net/note/delete/89009/useless
Del: bad code -- https://master.php.net/note/delete/89009/bad+code
Del: spam -- https://master.php.net/note/delete/89009/spam
Del: non-english -- https://master.php.net/note/delete/89009/non-english
Del: in docs -- https://master.php.net/note/delete/89009/in+docs
Del: other reasons-- https://master.php.net/note/delete/89009
Reject -- https://master.php.net/note/reject/89009
Search -- https://master.php.net/manage/user-notes.php