Skip to main content

code

How-to: Replace Keys of an Array in PHP

Posted in

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));
  }
}

Next, the class itself, after the jump.

Syndicate content