3v4l.org

run code in 300+ PHP versions simultaneously
<?php function filterTagsByTypes(array $tags, array $types, $count = 1) { $returnTags = []; sort($types); //Sort from low to high => high priority to low priority usort($tags, function($a, $b) { if ($a->type == $b->type) { return 0; } return $a->type > $b->type ? 1 : -1; }); //Sort tags array from low type to high type. foreach ($types as $type) { foreach ($tags as $tag) { //In this case, since both arrays are sorted, the priority //you are looking for will not arrive. if ($tag->type > $type) { break; //So break out and continue to the next type. } if ($tag->type == $type) { $returnTags[] = $tag; } if (count($returnTags) >= $count) { //End it now! return $returnTags; } } } } // Usage: class Tag { private $type; function __construct($type) { $this->type = $type; } } $tags = [ new Tag(50), new Tag(1), new Tag(25) ]; $types = [1, 50]; var_dump(filterTagsByTypes($tags, $types));

preferences:
35.78 ms | 402 KiB | 5 Q