3

Say I have a shape like this

$something = shape(
  'some_key' => ...,
  'another_key' => ...,
  ...
);

How can I iterate each field of the shape? I'm looking for something like this

foreach ($something as $key) {
  ...
}
kebab-case
  • 1,732
  • 1
  • 13
  • 24
  • Note that while the answer below answers your question, you should consider if a shape is actually the right data structure -- if you need to iterate the structure, a dictionary might be more suitable. (Shapes are great when you have fixed keys and thus pull out specific keys -- if you need to iterate, that often sounds like a dict!) – Josh Watzman Nov 16 '20 at 21:06
  • @JoshWatzman Thanks for the input, I was attempting to implement my change to pre-existing code which was currently using shapes. – kebab-case Nov 17 '20 at 21:03

1 Answers1

7

Convert to a dict first with the built-in HH\Shapes::toDict then iterate:

foreach(HH\Shapes::toDict($something) as $k => $v) {
  // ...
}
concat
  • 3,107
  • 16
  • 30