5

If I assign values to array like this:

$foo[0] = 2;
$foo[1] = 3;
print_r($foo);

I get:

Array
(
    [0] => 2
    [1] => 3
)

But if I do:

$foo[1] = 3;
$foo[0] = 2 ;
print_r($foo);

I get:

Array
(
    [1] => 3
    [0] => 2
)

As you can see first goes array with index 1 and it confuses me, is it possible to make that it would start from 0

If you interested, I assign value to array with index 1 because I need to use that value for calculating array with index 0

2
  • 1
    What is your exact problem? I doubt that print_r is the final use you have for that $foo. Could it be that this is a presentation issue only? If you access $foo[0] you'll still get the same result, sorted or not. You could ofcourse use the ksort() option provided in the answers, but first consider if you need it. Commented Sep 12, 2011 at 13:50
  • @Nanne just for debugging, I will remove them, but it's really annoying, because in all other examples it goes from 0 and there it's from 1 Commented Sep 12, 2011 at 13:56

3 Answers 3

8

try to use ksort();. It sorts your keys ascending

<?php
$foo[1] = 3;
$foo[0] = 2 ;
ksort($foo);
print_r($foo);

results in

Array ( 
   [0] => 2 
   [1] => 3 
) 

demo

Sign up to request clarification or add additional context in comments.

5 Comments

Perhaps an explanation of why Templar sees the behavior he sees, and then maybe an explanation of what ksort() does would be helpful.
@Templar: because it should be sorted first. This function returns boolean
You can check the manual: Returns TRUE on success or FALSE on failure. that line prints that returnvalue (probably true), and not the sorted array
Because ksort returns a boolean. You have to call ksort and then afterwords do a print_r on the array. The argument is passed as reference.
Yeah, you guys are too fast ;)
4

Try ksort()

The reason it is like this in PHP, is because arrays are a bit different from arrays in other languages. Arrays in PHP are somewhat similar to HashMaps in Java and Dictionaries in C#, although still a bit different.

2 Comments

@genesis, speed doesn't matter so much as quality.
@genesis, at least he provided some explanation of what was happening.
-3

You can also add

$foo[0] = '';

,before you add any value to $foo[1]

1 Comment

It is not what he wants. he said "HOW to sort array keys"... not "HOW to workaround it"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.