1

I have two arrays, $country and $redirect with each entry corresponding with it's exact counterpart e.g. $redirect[1] and $country[1].

After un-setting values throughout the array, I might be left with, for example, an array where only $var[4] and $var[2] are set. I want to re-assign array keys from 0 upwards, so that $var[2] would have it's key re-assigned to $var[0] and $var[4] re-assigned to $var[1].

Essentially the sort() function, but sorting by current array key, as oppose to the numeric/string value of an array.

Is this possible?

Any answers or advice would be greatly appreciated ;)!

UPDATE:

I've attempted to use both ksort() and array_values(), however I'm not sure they're really what I need, as I plan on using the size_of() function.

My code:

$var = array(2 => "value_1", 4 => "value_2", 6 => "value_3");
ksort($var);
for($i = 0, $size = sizeof($var); $i < $size; $i++) {
    $var[$i] = "foo";
}
var_dump($var);

Returns:

array(5) { [2]=> string(3) "foo" [4]=> string(7) "value_2" [6]=> string(7) "value_3" [0]=> string(3) "foo" [1]=> string(3) "foo" }

Any additional ideas/answers on how I could get this to work would be greatly appreciated!

1 Answer 1

2

Use array_values() (returns "sorted" array):

$var = array(2 => "value_1", 4 => "value_2", 6 => "value_3");
$var = array_values($var);
for($i = 0, $size = sizeof($var); $i < $size; $i++) {
    $var[$i] = "foo";
}
var_dump($var);
5
  • Huge thanks, I'll accept your answer when the timer drops ;)!
    – Avicinnian
    Commented Aug 22, 2011 at 20:42
  • Oh, is there any reason to use array_values() over ksort()?
    – Avicinnian
    Commented Aug 22, 2011 at 20:43
  • No. ksort() will work the best in your case as it works in-place.
    – piotrp
    Commented Aug 22, 2011 at 20:45
  • Actually, I'm not sure that's what I'm looking for, as it doesn't seem to re-sort the array, at least in this example (pastebin.com/xWEuK48j). The reason I need it, is so that I can use the sizeof() function in conjunction with a for() loop, as demonstrated in that example. Any idea of what I could do?
    – Avicinnian
    Commented Aug 22, 2011 at 21:08
  • Edited answer. You need array_values().
    – piotrp
    Commented Aug 22, 2011 at 21:19

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.