note 89009 rejected from control-structures.foreach by thiago
| From: | thiago@php.net | Date: | Wed, 18 Feb 2009 11:55:51 +0000 |
| Subject: | note 89009 rejected from control-structures.foreach by thiago | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-150783@lists.php.net to get a copy of this message | ||
Note Submitter: peter dot swietoslawski at gmail dot com
----
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().