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 );
  • \$\begingroup\$ I just had a thought to possibly implement Iterator instead of IteratorAggregate which would reduce the need for duplicating the array before iterating, and instead, decode during the iteration. \$\endgroup\$ – zzzzBov Mar 10 '11 at 23:51

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)
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.