So I have a function that currently has a foreach and it works amazing, but I’m being forced to change it to a while loop:
PLEASE NOTE: The developers at my company don’t want to use the foreach and they think that a while loop would be more efficient, but I’m not understanding how that would be executed, so I need some help.
So I have the following function ($post_blocks
is an array of arrays):
public function parse_block_data(string $block_name, string $selector, $post_id) { if (!has_blocks($post_id)) { return false; } $post_blocks = parse_blocks(get_the_content('', false, $post_id)); foreach ($post_blocks as $block) { if ($block_name != $block['blockName']) { continue; } if (!isset($block['attrs']['id'])) { return false; } if (isset($block['attrs']['data'][$selector])) { return $block['attrs']['data'][$selector]; } else { break; } } return false; }
It uses the parameters to build up an array as shown below:
Output
So I started building a while loop inside the function, but I’m clueless on how to achieve it without using a foreach or if it’s even possible, so I replaced the foreach with:
// I get the 9 counts of $post_blocks correctly. $block = 0; while ($block < count($post_blocks)) // If the $block_name doesn't match `blockName` value inside the multi-dimensional array, then continue iterating until the end and then return false. // If ['attrs']['id'] is not set, return false. // At last, if we have a blockName and a ID and the selector is set, return ['attrs']['data'][$selector] }
All help will be appreciated! It makes no sense to me, but if someone can assist, I’d be forever grateful!
Advertisement
Answer
It’s basically the same as your foreach
loop, you just set the iteration variable by indexing the array, and increment the index manually.
$block_num = 0; while ($block_num < count($post_blocks)) { $block = $post_blocks[$block_num]; if ($block_name == $block['blockName']) { if (!isset($block['attrs']['id'])) { return false; } if (isset($block['attrs']['data'][$selector])) { return $block['attrs']['data'][$selector]; } else { break; } } $block_num++; }
I’m not sure why your colleagues think this is preferable.
If there’s a company coding style they want you to follow, why don’t you ask them what it should be?