HiveBrain v1.2.0
Get Started
← Back to all entries
patternphpMinor

Decoding name/value pairs

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
pairsnamevaluedecoding

Problem

I have this code in a class sharing a private static array of data. Internally it's encoded, but I need the iterator for a foreach loop to show the decoded values.

Is there a native array function that can remap the keys and values via a callback function?

public function getIterator( )
{
  $arr = array();
  foreach ( self::$data as $encName => $encValue )
  {
    $name = $this->decode( $encName );
    $value = $this->decode( $encValue );
    $arr[$name] = $value;
  }
  return new ArrayIterator( $arr );
}

Solution

Implementing Iterator is the way to go in my opinion. As for your question, array_map would allow you to decode the values but not the keys. But you can combine that with other array operations to get the desired result.

public function decodeArray($array) {
    $decode = array($this, 'decode');
    return array_combine(
            array_map(array_keys($array), $decode),
            array_map(array_values($array), $decode)
        );
}

Code Snippets

public function decodeArray($array) {
    $decode = array($this, 'decode');
    return array_combine(
            array_map(array_keys($array), $decode),
            array_map(array_values($array), $decode)
        );
}

Context

StackExchange Code Review Q#1238, answer score: 6

Revisions (0)

No revisions yet.