How to sort an array by key to match another array’s order by key [PHP]

sometime you have two arrays, both have the same keys (different values) however array #2 is in a different order. you want to be able to resort the second array so it is in the same order as the first array.

Is there a function that can quickly do this?

yups to do this you can use foreach and reorder array #2 like below:

$arr1 = array(
    'a' => '42', 
    'b' => '551',
    'c' => '512',
    'd' => 'gge',
) ;

$arr2 = array(
    'd' => 'ordered',
    'b' => 'is',
    'c' => 'now',
    'a' => 'this', 
) ;

$arr2ordered = array() ;

foreach (array_keys($arr1) as $key) {
    $arr2ordered[$key] = $arr2[$key] ;


then the result will be like this:

Array ( [a] => this [b] => is [c] => now [d] => ordered )

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.