Hack Iterate (Map) over Map

Hack Iterate (Map) over Map

I have a Map such as:

$m = Map {
  'sort' => 'created',
  'order' => 'desc',
}

I want to turn that into a string:

'sort:created order:desc'

I can do this with arrays as explained in this SO answer:

implode(' ', array_map(($k, $v) ==> $k.':'.$v, array_keys($m), $m))

I've read the documentation of Map::items and tried:

$m->items()->map(($key, $value) ==> print($key))

But this prints nothing.

I'm looking for a oneliner like with the arrays, no loops.

2 Answers

map()'s parameter is a function that only takes one argument; if you run the typechecker, it will tell you this:

test.php:9:20,20: Invalid argument (Typing[4039])
  /tmp/hh_server/hhi_1ebd4af3/hhi/interfaces.hhi:363:27,44: Number of  arguments doesn't match
  test.php:9:20,20: Because of this definition

What you want is mapWithKey() :

$m->mapWithKey(($key, $value) ==> print($key));

You can also use exactly the same code you were using for arrays:

0

Use:

implode(' ', $m->mapWithKey(($k, $v) ==> $k.':'.$v))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Sarah Jenkins
Author

Sarah Jenkins

Sarah Jenkins is a veteran tech journalist with over 12 years of experience covering artificial intelligence, mobile innovations, and digital ethics. Her insights have appeared in leading technology publications worldwide.