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);
Sign up to request clarification or add additional context in comments.

5 Comments

Huge thanks, I'll accept your answer when the timer drops ;)!
Oh, is there any reason to use array_values() over ksort()?
No. ksort() will work the best in your case as it works in-place.
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?
Edited answer. You need array_values().

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.