lstrojny/hmmmath
PHP math utility package providing common numeric helpers and algorithms. Useful for calculations, statistics-like operations, and reusable math functions in Laravel or any PHP project. Lightweight, dependency-friendly, and easy to integrate into existing codebases.
Installation
composer require lstrojny/hmmmath
No additional configuration is required—just autoload the package.
First Use Case: Basic Math Operations
use Lstrojny\HmmMath\Math;
$result = Math::sum([1, 2, 3]); // 6
$result = Math::avg([1, 2, 3]); // 2
Where to Look First
Lstrojny\HmmMath\Math (static methods for operations).php artisan vendor:publish --tag=hmmmath-config (if config exists).tests/ directory in the package for usage patterns.Basic Arithmetic
$sum = Math::sum([10, 20, 30]);
$product = Math::product([2, 3, 4]); // 24
$mean = Math::avg([1, 2, 3, 4, 5]); // 3
Statistical Functions
$median = Math::median([1, 3, 2]); // 2
$mode = Math::mode([1, 2, 2, 3]); // 2
$stdDev = Math::stdDev([1, 2, 3, 4, 5]); // ~1.41
Integration with Laravel
$this->app->bind('math', function () {
return new \Lstrojny\HmmMath\Math();
});
app/Helpers/MathHelper.php):
if (!function_exists('math')) {
function math($operation, $data) {
return \Lstrojny\HmmMath\Math::$operation($data);
}
}
Usage:
$result = math('sum', [1, 2, 3]); // 6
Batch Processing
$data = [10, 20, 30, 40, 50];
$stats = [
'sum' => Math::sum($data),
'avg' => Math::avg($data),
'max' => Math::max($data),
];
Custom Logic with Chaining
$result = Math::sum([1, 2, 3])
->multiply(2) // 12
->subtract(4); // 8
Input Validation
$cleanData = array_filter($rawData, fn($val) => is_numeric($val));
$result = Math::sum($cleanData);
Edge Cases
null or throw errors (check method docs).Math::mode() returns the first mode if multiple exist (behavior may vary).Performance
$generator = function() {
yield 1; yield 2; yield 3; // etc.
};
$sum = Math::sum(iterator_to_array($generator()));
Enable Error Reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);
Log Intermediate Results
$data = [1, 2, 3];
\Log::debug('Input data:', ['data' => $data]);
$result = Math::sum($data);
\Log::debug('Result:', ['result' => $result]);
Test Edge Cases
$this->assertEquals(0, Math::sum([])); // If supported
$this->assertNull(Math::mode([])); // If unsupported
Custom Functions
Math class or create a wrapper:
class ExtendedMath extends \Lstrojny\HmmMath\Math {
public static function customOperation($data) {
return self::sum($data) * 2;
}
}
Configuration
php artisan vendor:publish --tag=hmmmath-config
config/hmmmath.php (if exists) for defaults (e.g., precision for stdDev).Integration with Laravel Collections
$collection = collect([1, 2, 3]);
$sum = $collection->sum(); // Native Laravel
// OR
$sum = Math::sum($collection->toArray());
Precision Handling
bcmath or gmp:
$result = Math::sum([1.1, 2.2], 2); // Round to 2 decimal places
How can I help you explore Laravel packages today?