silkfire Posted October 8, 2012 Share Posted October 8, 2012 Can someone guide me on the most effective way of doing this? 1. I got an array where some keys have a specified numeric key. 2. I want to sort this array in such a way that those elements without a specified numeric key must get a key. If it exists, then increment. Before: array(1 => 'val1', 4 => 'valY', 'valX', 'valZ', 'valN'); After: array(0 => 'valX', 1 => 'val1', 2 => 'valZ', 3 => 'valN', 4 => 'valY'); Thanks in advance! Quote Link to comment https://forums.phpfreaks.com/topic/269219-order-array/ Share on other sites More sharing options...
Barand Posted October 8, 2012 Share Posted October 8, 2012 (edited) You will find they all have keys. Try $before = array(1 => 'val1', 4 => 'valY', 'valX', 'valZ', 'valN'); echo '<pre>', print_r($before, 1), '</pre>'; If a key isn't specified it is allocated the next highest integer key Edited October 8, 2012 by Barand Quote Link to comment https://forums.phpfreaks.com/topic/269219-order-array/#findComment-1383662 Share on other sites More sharing options...
ManiacDan Posted October 8, 2012 Share Posted October 8, 2012 Right, every array element has a key, and if none is specified they are automatically numbered starting at zero, unless you manually set a numeric key. Quote Link to comment https://forums.phpfreaks.com/topic/269219-order-array/#findComment-1383664 Share on other sites More sharing options...
silkfire Posted October 8, 2012 Author Share Posted October 8, 2012 I tried to var_dump this array and the other elements start at 5, not 0 =( Quote Link to comment https://forums.phpfreaks.com/topic/269219-order-array/#findComment-1383665 Share on other sites More sharing options...
Barand Posted October 8, 2012 Share Posted October 8, 2012 That's right - the previous specified key was 4 Quote Link to comment https://forums.phpfreaks.com/topic/269219-order-array/#findComment-1383666 Share on other sites More sharing options...
silkfire Posted October 8, 2012 Author Share Posted October 8, 2012 That doesn't solve my problem stiill.... Quote Link to comment https://forums.phpfreaks.com/topic/269219-order-array/#findComment-1383672 Share on other sites More sharing options...
ManiacDan Posted October 8, 2012 Share Posted October 8, 2012 What is your problem then? Why do you absolutely need key #2? Why does it matter if the association between key #4 and its data is lost? Quote Link to comment https://forums.phpfreaks.com/topic/269219-order-array/#findComment-1383673 Share on other sites More sharing options...
Barand Posted October 8, 2012 Share Posted October 8, 2012 No, it doesn't solve your problem but it does mean you need to rethink it. Quote Link to comment https://forums.phpfreaks.com/topic/269219-order-array/#findComment-1383701 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.