3v4l.org

run code in 150+ php & hhvm versions
Bugs & Features
<?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));
Output for 7.0.0 - 7.1.0
Fatal error: Uncaught Error: Cannot access private property Tag::$type in /in/99BBI:7 Stack trace: #0 [internal function]: {closure}(Object(Tag), Object(Tag)) #1 /in/99BBI(11): usort(Array, Object(Closure)) #2 /in/99BBI(46): filterTagsByTypes(Array, Array) #3 {main} thrown in /in/99BBI on line 7
Process exited with code 255.
Output for 5.4.0 - 5.6.28
Fatal error: Cannot access private property Tag::$type in /in/99BBI on line 7
Process exited with code 255.
Output for 5.1.0 - 5.3.29
Parse error: syntax error, unexpected '[' in /in/99BBI on line 4
Process exited with code 255.
Output for 5.0.0 - 5.0.5
Parse error: parse error, unexpected T_ARRAY, expecting '&' or T_VARIABLE in /in/99BBI on line 3
Process exited with code 255.
Output for 4.4.2 - 4.4.9
Parse error: syntax error, unexpected T_ARRAY, expecting ')' in /in/99BBI on line 3
Process exited with code 255.
Output for 4.3.0 - 4.3.1, 4.3.5 - 4.4.1
Parse error: parse error, unexpected T_ARRAY, expecting ')' in /in/99BBI on line 3
Process exited with code 255.
Output for 4.3.2 - 4.3.4
Parse error: parse error, expecting `')'' in /in/99BBI on line 3
Process exited with code 255.