# ksort an array internally (OR: interate a numerically-indexed array with respect to the indeces)

- Thread: https://externals.io/message/55676
- Original archive: https://news-web.php.net/php.internals/55676
- Started by Flavius Aspra on 2011-10-01T17:01:03+00:00
- Messages: 1
- Reply by email to internals@lists.php.net
- More for agents: search with https://externals.io/search.md?q={query} · JSON API at https://externals.io/api · documentation at https://externals.io/llms.txt

---

## #55676 — Flavius Aspra — 2011-10-01T17:01:03+00:00

URL: https://externals.io/message/55676#55676

Hi

How can I `ksort()` an array?

The default implementation does basically this: 
zend_hash_sort(Z_ARRVAL_P(array), zend_qsort, php_array_key_compare, 0 
TSRMLS_CC) but php_array_key_compare() is static in ext/standard/array.c [1]

Actually I wouldn't need to sort by key at all if add_index_zval() would 
put the zval at the "right" [2] place from the beginning. Is there any 
better alternative to add_index_zval() in this regard?

Preferably without going through the hassle of making a round-trip via 
zend_call_function() "directly" to zif_ksort().

What I need is to zend_hash_move_forward() & co but to get the elements 
in the order indicated by the numeric indeces.

Thanks,
Flavius


[1] http://lxr.php.net/opengrok/xref/PHP_5_3/ext/standard/array.c#250
[2] I know the HT implementation is made to be generalized enough for 
other use cases, and as such, there is no "right" order. Thus I'm 
thinking maybe there's some way to add a new numerically-indexed element 
to the HT and "teach" the HT to do the bookkeeping in respect to the 
numeric order. Or maybe a better way to iterate such an array.

-- 
What I cannot create, I do not understand. -- Feynman
