Martin AJ Martin AJ - 4 months ago 8
PHP Question

How can I separate numeric array's keys from the letter keys?

Here is my code:

$arr = array();
$arr[] = 1;
$arr['txt'] = 'something';
$arr['txt2'] = 'something2';
$arr[] = 2;
$arr[] = 3;

echo '<pre>';
print_r($arr);

/* output:
1
something
something2
2
3
*/


I'm trying to change array's order and make this result:

/* expected output:
1
2
3
something
something2
*/


As you see, I need to reindex all array's items and put the numeric ones in the beginning of array. Is that possible?

Answer

Simplest way is to sort the array by key. using ksort which modifies the array in place. Use the SORT_STRING flag to get the result you seek:

ksort($myArr, SORT_STRING);

Live demo

Comments