tags:

views:

213

answers:

3
$a = array(0=>'a',1=>'b',2=>'c', 3=>'d');

I want to change the order to be 3,2,0,1

$a = array(3=>'d',2=>'c',0=>'a', 1=>'b');
+3  A: 

If you want to change the order programmatically, have a look at the various array sorting functions in PHP, especially

  • uasort()— Sort an array with a user-defined comparison function and maintain index association
  • uksort()— Sort an array by keys using a user-defined comparison function
  • usort()— Sort an array by values using a user-defined comparison function

Based on Yannicks example below, you could do it this way:

$a = array(0 => 'a', 1 => 'b', 2 => 'c', 3 => 'd');
$b = array(3, 2, 0, 1); // rule indicating new key order
$c = array();
foreach($b as $index) {
    $c[$index] = $a[$index];
}
print_r($c);

would give

Array([3] => d [2] => c [0] => a [1] => b)

But like I said in the comments, if you do not tell us the rule by which to order the array or be more specific about your need, we cannot help you beyond this.

Gordon
I need to change the order programmatically.
@unknown By what rules? Neither `0,1,2,3` => `3,2,0,1` nor `a,b,c,d` => `d,c,a,b` reveal any specific logic. It looks arbitrary to me. Tell us more about your usecase/need.
Gordon
The rule has nothing to do about this question.And the rule can be arbitary,just generated somehow that has nothing to do with this very question.
If you are after reordering an array, *the rule* has everything to do about the question. Anyway, I've updated the answer.
Gordon
A: 

here is how

krsort($a);
Sarfraz
He does not want to reverse the order. It is `3,2,0,1` not `3,2,1,0`
Gordon
+3  A: 

Since arrays in PHP are actually ordered maps, I am unsure if the order of the items is preserved when enumerating.

If you simply want to enumerate them in a specific order:

$a = array(0=>'a',1=>'b',2=>'c', 3=>'d');
$order = array(3, 2, 0, 1);

foreach ($order as $index)
{
  echo "$index => " . $a[$index] . "\n";
}
Yannick M.
Is there another way than iterating?
What exactly are you trying to do? Because I cannot see another reason why to change the 'order' of the elements in the array apart from enumerating the collection in a certain order.
Yannick M.