Submitted by boydjd on Thu, 10/09/2008 - 02:19
I had a need tonight to replace the keys in an array in PHP. I couldn't find a good solution on any mailing lists or other sites, so I thought I'd share the class that I came up with, and it's test.
First up, the test:
<?php
require_once 'PHPUnit/Framework.php';
require_once 'ArrayHelper.class.php';
class ArrayHelperTest extends PHPUnit_Framework_TestCase
{
public function testRenameKeys()
{
$keys = array('newkey1',
'newkey2',
'newkey3');
$array = array('oldkey1' => 'value1',
'oldkey2' => 'value2',
'oldkey3' => 'value3');
ArrayHelper::renameKeys($array,$keys);
$this->assertArrayHasKey($keys[0],$array);
$this->assertArrayHasKey($keys[1],$array);
$this->assertArrayHasKey($keys[2],$array);
$this->assertEquals(3,count($array));
}
}
require_once 'PHPUnit/Framework.php';
require_once 'ArrayHelper.class.php';
class ArrayHelperTest extends PHPUnit_Framework_TestCase
{
public function testRenameKeys()
{
$keys = array('newkey1',
'newkey2',
'newkey3');
$array = array('oldkey1' => 'value1',
'oldkey2' => 'value2',
'oldkey3' => 'value3');
ArrayHelper::renameKeys($array,$keys);
$this->assertArrayHasKey($keys[0],$array);
$this->assertArrayHasKey($keys[1],$array);
$this->assertArrayHasKey($keys[2],$array);
$this->assertEquals(3,count($array));
}
}
Next, the class itself, after the jump.
<?php
/**
* A collection of methods for array manipulation
**/
class ArrayHelper
{
/**
* Replaces the keys in the given array with an array of in-order
* replacement keys.
*
* @param array &$array
* @param array $replacement_keys
**/
public static function renameKeys(&$array, $replacement_keys)
{
$keys = array_keys($array);
$values = array_values($array);
for ($i=0; $i < count($replacement_keys); $i++) {
$keys[$i] = $replacement_keys[$i];
}
$array = array_combine($keys, $values);
}
} //END ArrayHelper
/**
* A collection of methods for array manipulation
**/
class ArrayHelper
{
/**
* Replaces the keys in the given array with an array of in-order
* replacement keys.
*
* @param array &$array
* @param array $replacement_keys
**/
public static function renameKeys(&$array, $replacement_keys)
{
$keys = array_keys($array);
$values = array_values($array);
for ($i=0; $i < count($replacement_keys); $i++) {
$keys[$i] = $replacement_keys[$i];
}
$array = array_combine($keys, $values);
}
} //END ArrayHelper
At present, renameKeys() only supports your standard, run-of-the-mill single-dimension array, but using it on a two-dimensional array is no big deal:
<?php
foreach($arrayList as &$array)
{
ArrayHelper::renameKeys($array,$keys);
}
foreach($arrayList as &$array)
{
ArrayHelper::renameKeys($array,$keys);
}
Hope this is helpful to somebody out there other than me ;)
Trackback URL for this post:
http://www.jbip.net/trackback/66

Why the loop?
hanks for the advice, but...
Would this not do the trick?
No, array_combine requires
No, array_combine requires that all of the keys be unique.
thank you!!!
thank you!!!