3v4l.org

run code in 200+ php & hhvm versions
Bugs & Features
<?php class ArrayAnalyzer { /** * The rules to test. * * @var array */ protected $rules; public function __construct(ArrayAnalyzerRule ...$rules) { $this->rules = $rules; } /** * Analyzes an array with each of the rules, and returns the report. * * @param array $array * @return array */ public function analyze(array $array) { $report = []; foreach ($this->rules as $key => $rule) { if ($rule->fulfilledBy($array)) { $report[$key] = $rule->getValue($array); } } return $report; } } interface ArrayAnalyzerRule { /** * Checks whether the rule is fulfilled by the passed array. * * @param array $array * @return boolean */ public function fulfilledBy(array $array); /** * Gets the rule output value. * * @param array $array * @return array */ public function getValue(array $array); } class AllIntegersRule implements ArrayAnalyzerRule { /** * {@inheritDoc} */ public function fulfilledBy(array $array) { return array_reduce($array, function ($carry, $item) { return $carry && is_int($item); }, true); } /** * {@inheritDoc} */ public function getValue(array $array) { return true; } } class SameLengthRule implements ArrayAnalyzerRule { public function fulfilledBy(array $array) { return count(array_unique(array_map(function ($item) { return mb_strlen($item); }, $array))) === 1; } /** * {@inheritDoc} */ public function getValue(array $array) { return mb_strlen($array[0]); } } $arrayAnalyzer = new ArrayAnalyzer([ 'isInteger' => new AllIntegersRule, 'length' => new SameLengthRule, ]); var_dump($arrayAnalyzer->analyze([1, 2, 3])); var_dump($arrayAnalyzer->analyze([1, 2, 'D'])); var_dump($arrayAnalyzer->analyze([1, 2, '3D']));
based on TUsU3
Output for 7.0.0 - 7.2.0
Fatal error: Uncaught TypeError: Argument 1 passed to ArrayAnalyzer::__construct() must implement interface ArrayAnalyzerRule, array given, called in /in/YHs7h on line 97 and defined in /in/YHs7h:12 Stack trace: #0 /in/YHs7h(97): ArrayAnalyzer->__construct(Array) #1 {main} thrown in /in/YHs7h on line 12
Process exited with code 255.
Output for 5.6.7 - 5.6.28
Catchable fatal error: Argument 1 passed to ArrayAnalyzer::__construct() must implement interface ArrayAnalyzerRule, array given, called in /in/YHs7h on line 98 and defined in /in/YHs7h on line 12
Process exited with code 255.
Output for 5.4.2 - 5.5.35
Parse error: syntax error, unexpected '.', expecting '&' or variable (T_VARIABLE) in /in/YHs7h on line 12
Process exited with code 255.
Output for 5.3.17 - 5.3.29
Parse error: syntax error, unexpected '.', expecting '&' or T_VARIABLE in /in/YHs7h on line 12
Process exited with code 255.