Download the PHP package hi-folks/statistics without Composer

On this page you can find all versions of the php package hi-folks/statistics. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.

FAQ

After the download, you have to make one include require_once('vendor/autoload.php');. After that you have to import the classes with use statements.

Example:
If you use only one package a project is not needed. But if you use more then one package, without a project it is not possible to import the classes with use statements.

In general, it is recommended to use always a project to download your libraries. In an application normally there is more than one library needed.
Some PHP packages are not free to download and because of that hosted in private repositories. In this case some credentials are needed to access such packages. Please use the auth.json textarea to insert credentials, if a package is coming from a private repository. You can look here for more information.

  • Some hosting areas are not accessible by a terminal or SSH. Then it is not possible to use Composer.
  • To use Composer is sometimes complicated. Especially for beginners.
  • Composer needs much resources. Sometimes they are not available on a simple webspace.
  • If you are using private repositories you don't need to share your credentials. You can set up everything on our site and then you provide a simple download link to your team member.
  • Simplify your Composer build process. Use our own command line tool to download the vendor folder as binary. This makes your build process faster and you don't need to expose your credentials for private repositories.
Please rate this library. Is it a good library?

Informations about the package statistics

PHP package for Statistics

Statistics PHP package

Latest Version on Packagist Total Downloads
Static Code analysis Packagist License
Packagist PHP Version Support GitHub last commit

Tests

A PHP package for descriptive statistics, normal distribution, outlier detection, and streaming analytics on numeric data.

This package provides a comprehensive set of statistical functions for PHP: descriptive statistics (mean, median, mode, standard deviation, variance, quantiles), robust measures (trimmed mean, weighted median, median absolute deviation), distribution modelling (normal distribution with PDF, CDF, and inverse CDF), outlier detection (z-score and IQR-based), z-scores, percentiles, coefficient of variation, frequency tables, correlation, regression (linear, logarithmic, power, and exponential), kernel density estimation, and O(1) memory streaming statistics.

It works with any numeric dataset — from sports telemetry and sensor data to race results, survey responses, and financial time series.

Articles and resources:

This package is inspired by the Python statistics module

Installation

You can install the package via composer:

Usage

Stat class

Stat class has methods to calculate an average or typical value from a population or sample. This class provides methods for calculating mathematical statistics of numeric data. The various mathematical statistics are listed below:

Mathematical Statistic Description
mean() arithmetic mean or "average" of data
fmean() floating-point arithmetic mean, with optional weighting and precision
trimmedMean() trimmed (truncated) mean — mean after removing outliers from each side
median() median or "middle value" of data
weightedMedian() weighted median — median with weights, where each value has a different importance
medianLow() low median of data
medianHigh() high median of data
medianGrouped() median of grouped data, using interpolation
mode() single mode (most common value) of discrete or nominal data
multimode() list of modes (most common values) of discrete or nominal data
quantiles() cut points dividing the range of a probability distribution into continuous intervals with equal probabilities (supports exclusive and inclusive methods)
thirdQuartile() 3rd quartile, is the value at which 75 percent of the data is below it
firstQuartile() first quartile, is the value at which 25 percent of the data is below it
percentile() value at any percentile (0–100) with linear interpolation
rank() rank each data point, with configurable tie handling
percentileRank() percentile position of a value within a dataset
pstdev() Population standard deviation
stdev() Sample standard deviation
sem() Standard error of the mean (SEM) — measures precision of the sample mean
meanAbsoluteDeviation() mean absolute deviation (MAD) — average distance from the mean
medianAbsoluteDeviation() median absolute deviation — median distance from the median, robust to outliers
pvariance() variance for a population (supports pre-computed mean via mu)
variance() variance for a sample (supports pre-computed mean via xbar)
skewness() adjusted Fisher-Pearson sample skewness
pskewness() population (biased) skewness
kurtosis() excess kurtosis (sample formula, 0 for normal distribution)
coefficientOfVariation() coefficient of variation (CV%), relative dispersion as percentage
zscores() z-scores for each value — how many standard deviations from the mean
outliers() outlier detection based on z-score threshold
iqrOutliers() outlier detection based on IQR method (box plot whiskers), robust for skewed data
geometricMean() geometric mean
harmonicMean() harmonic mean
correlation() Pearson’s, Spearman’s rank, or Kendall tau correlation coefficient for two inputs
kendallTau() Kendall tau-b rank correlation coefficient for ordinal association with tie handling
covariance() the sample covariance of two inputs
linearRegression() return the slope and intercept of simple linear regression parameters estimated using ordinary least squares (supports proportional: true for regression through the origin)
logarithmicRegression() logarithmic regression — fits y = a × ln(x) + b, ideal for diminishing returns patterns (e.g., athletic improvement, learning curves)
powerRegression() power regression — fits y = a × x^b, useful for power law relationships
exponentialRegression() exponential regression — fits y = a × e^(b×x), useful for exponential growth or decay
rSquared() coefficient of determination (R²) — proportion of variance explained by linear regression
confidenceInterval() confidence interval for the mean using the normal (z) distribution
zTest() one-sample Z-test — tests whether the sample mean differs significantly from a hypothesized population mean
tTest() one-sample t-test — like z-test but appropriate for small samples where the population standard deviation is unknown
tTestTwoSample() two-sample independent t-test (Welch's) — compares the means of two independent groups without assuming equal variances
tTestPaired() paired t-test — tests whether the mean difference between paired observations is significantly different from zero
chiSquaredTest() chi-squared goodness-of-fit test for observed vs expected category counts
chiSquaredIndependence() chi-squared test of independence for contingency tables
kde() kernel density estimation — returns a closure that estimates the probability density (or CDF) at any point
kdeRandom() random sampling from a kernel density estimate — returns a closure that generates random floats from the KDE distribution

Stat::mean( array $data )

Return the sample arithmetic mean of the array $data. The arithmetic mean is the sum of the data divided by the number of data points. It is commonly called “the average”, although it is only one of many mathematical averages. It is a measure of the central location of the data.

Stat::fmean( array $data, array|null $weights = null, int|null $precision = null )

Return the arithmetic mean of the array $data, as a float, with optional weights and precision control. This function behaves like mean() but ensures a floating-point result and supports weighted datasets. If $weights is provided, it computes the weighted average. The result is rounded to a given decimal $precision. The result is rounded to $precision decimal places. If $precision is null, no rounding is applied — this may lead to results with long or unexpected decimal expansions due to the nature of floating-point arithmetic in PHP. Using rounding helps ensure cleaner, more predictable output.

If the input is empty, or weights are invalid (e.g., length mismatch or sum is zero), an exception is thrown. Use this function when you need floating-point accuracy or to apply custom weighting and rounding to your average.

Stat::trimmedMean( array $data, float $proportionToCut = 0.1, ?int $round = null )

Return the trimmed (truncated) mean of the data. Computes the mean after removing the lowest and highest fraction of values. This is a robust measure of central tendency, less sensitive to outliers than the regular mean.

The $proportionToCut parameter specifies the fraction to trim from each side (must be in the range [0, 0.5)). For example, 0.1 removes the bottom 10% and top 10%.

Stat::geometricMean( array $data )

The geometric mean indicates the central tendency or typical value of the data using the product of the values (as opposed to the arithmetic mean which uses their sum).

Stat::harmonicMean( array $data )

The harmonic mean is the reciprocal of the arithmetic mean() of the reciprocals of the data. For example, the harmonic mean of three values a, b, and c will be equivalent to 3/(1/a + 1/b + 1/c). If one of the values is zero, the result will be zero.

You can also calculate the harmonic weighted mean. Suppose a car travels 40 km/hr for 5 km, and when traffic clears, speeds up to 60 km/hr for the remaining 30 km of the journey. What is the average speed?

where:

Stat::median( array $data )

Return the median (middle value) of numeric data, using the common “mean of middle two” method.

Stat::weightedMedian( array $data, array $weights, ?int $round = null )

Return the weighted median of the data. The weighted median is the value where the cumulative weight reaches 50% of the total weight. This is useful for survey data, financial analysis, or any dataset where observations have different importance.

All weights must be positive numbers and the weights array must have the same length as the data array.

Stat::medianLow( array $data )

Return the low median of numeric data. The low median is always a member of the data set. When the number of data points is odd, the middle value is returned. When it is even, the smaller of the two middle values is returned.

Stat::medianHigh( array $data )

Return the high median of data. The high median is always a member of the data set. When the number of data points is odd, the middle value is returned. When it is even, the larger of the two middle values is returned.

Stat::medianGrouped( array $data, float $interval = 1.0 )

Estimate the median for numeric data that has been grouped or binned around the midpoints of consecutive, fixed-width intervals. The $interval parameter specifies the width of each bin (default 1.0). This function uses interpolation within the median interval, assuming values are evenly distributed across each bin.

For example, demographic data summarized into ten-year age groups:

Stat::quantiles( array $data, $n=4, $round=null, $method='exclusive' )

Divide data into n continuous intervals with equal probability. Returns a list of n - 1 cut points separating the intervals. Set n to 4 for quartiles (the default). Set n to 10 for deciles. Set n to 100 for percentiles which gives the 99 cut points that separate data into 100 equal-sized groups.

The $method parameter controls the interpolation method:

Stat::firstQuartile( array $data, $round=null )

The lower quartile, or first quartile (Q1), is the value under which 25% of data points are found when they are arranged in increasing order.

Stat::thirdQuartile( array $data, $round=null )

The upper quartile, or third quartile (Q3), is the value under which 75% of data points are found when arranged in increasing order.

Stat::percentile( array $data, float $p, ?int $round = null )

Return the value at the given percentile of the data, using linear interpolation between adjacent data points (exclusive method, consistent with quantiles()).

The percentile $p must be between 0 and 100. Requires at least 2 data points.

Stat::rank( array $data, string $method = Stat::RANK_AVERAGE )

Return 1-based ranks for each data point, preserving the original array keys.

The $method parameter controls how tied values are ranked:

Stat::percentileRank( array $data, int|float $value, string $kind = Stat::PERCENTILE_RANK_WEAK, ?int $round = null )

Return the percentile position of a value within a dataset.

The $kind parameter controls the calculation:

Stat::pstdev( array $data )

Return the Population Standard Deviation, a measure of the amount of variation or dispersion of a set of values. A low standard deviation indicates that the values tend to be close to the mean of the set, while a high standard deviation indicates that the values are spread out over a wider range.

Stat::stdev( array $data )

Return the Sample Standard Deviation, a measure of the amount of variation or dispersion of a set of values. A low standard deviation indicates that the values tend to be close to the mean of the set, while a high standard deviation indicates that the values are spread out over a wider range.

Stat::sem( array $data, ?int $round = null )

Return the standard error of the mean (SEM). SEM measures how precisely the sample mean estimates the population mean. It decreases as the sample size grows.

Formula: stdev / sqrt(n)

Requires at least 2 data points.

Stat::meanAbsoluteDeviation( array $data, ?int $round = null )

Return the mean absolute deviation (MAD) — the average of the absolute deviations from the mean.

MAD is a simple, intuitive measure of dispersion: it tells you "on average, how far values are from the mean". Unlike standard deviation, it does not square the differences, making it easier to interpret and somewhat less sensitive to outliers.

Use MAD when you want a straightforward, interpretable measure of spread, especially for reporting to non-technical audiences.

Stat::medianAbsoluteDeviation( array $data, ?int $round = null )

Return the median absolute deviation — the median of the absolute deviations from the median.

This is one of the most robust measures of dispersion available. Because it uses the median (not the mean) as the center and takes the median (not the mean) of deviations, it is highly resistant to outliers. Even if up to half the data points are extreme, the median absolute deviation remains stable.

Use it when your data may contain outliers, when you need a robust alternative to standard deviation, or for outlier detection (values far from the median in units of MAD are likely outliers).

Stat::variance ( array $data, ?int $round = null, int|float|null $xbar = null)

Variance is a measure of dispersion of data points from the mean. Low variance indicates that data points are generally similar and do not vary widely from the mean. High variance indicates that data values have greater variability and are more widely dispersed from the mean.

To calculate the variance from a sample:

If you have already computed the mean, you can pass it via xbar to avoid recalculation:

If you need to calculate the variance on the whole population and not just on a sample you need to use pvariance method. You can optionally pass the population mean via mu:

Stat::skewness ( array $data, ?int $round = null )

Skewness is a measure of the asymmetry of a distribution. The adjusted Fisher-Pearson formula is used, which is the same as Excel's SKEW() and Python's scipy.stats.skew(bias=False).

A positive skewness indicates a right-skewed distribution (tail extends to the right), while a negative skewness indicates a left-skewed distribution. A symmetric distribution has a skewness of 0.

Requires at least 3 data points.

If you need the population (biased) skewness instead of the sample skewness, use pskewness(). This is equivalent to scipy.stats.skew(bias=True):

Stat::kurtosis ( array $data, ?int $round = null )

Kurtosis measures the "tailedness" of a distribution — how much data lives in the extreme tails compared to a normal distribution. This method returns the excess kurtosis using the sample formula, which is the same as Excel's KURT() and Python's scipy.stats.kurtosis(bias=False).

A normal distribution has excess kurtosis of 0. Positive values (leptokurtic) indicate heavier tails and more outliers. Negative values (platykurtic) indicate lighter tails and fewer outliers.

Requires at least 4 data points.

Stat::coefficientOfVariation( array $data, ?int $round = null, bool $population = false )

The coefficient of variation (CV) is the ratio of the standard deviation to the mean, expressed as a percentage. It measures relative variability and is useful for comparing dispersion across datasets with different units or scales.

By default it uses the sample standard deviation. Pass population: true to use the population standard deviation instead.

Requires at least 2 data points (sample) or 1 (population). Throws if the mean is zero.

Stat::zscores( array $data, ?int $round = null )

Return the z-score for each value in the dataset. A z-score indicates how many standard deviations a value is from the mean. Z-scores are useful for standardizing data, comparing values from different distributions, and identifying outliers.

The z-scores of any dataset always sum to zero, and values beyond ±2 or ±3 are typically considered unusual or outliers.

Requires at least 2 data points and non-zero standard deviation.

Stat::outliers( array $data, float $threshold = 3.0 )

Return values from the dataset that are outliers based on z-score threshold. A value is considered an outlier if its absolute z-score exceeds the threshold.

The default threshold of 3.0 is a widely used convention — in a normal distribution, about 99.7% of values fall within 3 standard deviations of the mean, so values beyond that are rare. Use a lower threshold (e.g. 2.0) for stricter detection, or a higher one for more lenient filtering.

Stat::iqrOutliers( array $data, float $factor = 1.5 )

Return values that are outliers based on the Interquartile Range (IQR) method. A value is an outlier if it falls below Q1 - factor * IQR or above Q3 + factor * IQR. This is the same method used for box plot whiskers.

Unlike z-score based detection, the IQR method is robust — it does not assume a normal distribution and is not influenced by extreme values themselves. This makes it the preferred choice for skewed data or when the dataset may already contain outliers that would distort the mean and standard deviation.

Use factor: 1.5 (default) for mild outliers, or factor: 3.0 for extreme outliers only.

Example: Ski downhill race times

In a ski downhill race, most athletes finish between 108–116 seconds. A time of 200s (e.g. a crash/DNF) or 50s (e.g. a timing error) would be flagged as outliers:

Stat::covariance ( array $x , array $y )

Covariance, static method, returns the sample covariance of two inputs $x and $y. Covariance is a measure of the joint variability of two inputs.

Stat::correlation ( array $x , array $y, string $method = 'linear' )

Return the Pearson’s correlation coefficient for two inputs. Pearson’s correlation coefficient r takes values between -1 and +1. It measures the strength and direction of the linear relationship, where +1 means very strong, positive linear relationship, -1 very strong, negative linear relationship, and 0 no linear relationship.

Use $method = 'ranked' for Spearman’s rank correlation, which measures monotonic relationships (not just linear). Spearman’s correlation is computed by applying Pearson’s formula to the ranks of the data.

Use $method = 'kendall' for Kendall tau-b correlation, which measures ordinal association by comparing concordant and discordant pairs. Kendall tau-b is often useful for ordinal data, small samples, and datasets with ties.

Spearman’s rank correlation (non-linear but monotonic relationship):

Kendall tau-b rank correlation with ties:

Stat::kendallTau ( array $x , array $y, ?int $round = null )

Return Kendall's tau-b rank correlation coefficient for two inputs.

Stat::linearRegression ( array $x , array $y , bool $proportional = false )

Return the slope and intercept of simple linear regression parameters estimated using ordinary least squares. Simple linear regression describes the relationship between an independent variable $x and a dependent variable $y in terms of a linear function.

What happens in 2022, according to the samples above?

When proportional is true, the regression line is forced through the origin (intercept = 0). This is useful when the relationship between $x and $y is known to be proportional:

Stat::logarithmicRegression( array $x, array $y )

Fit a logarithmic model y = a × ln(x) + b. Returns [a, b].

This model naturally captures diminishing returns — fast initial change that gradually flattens. It is useful for data where early gains are large but improvement slows over time, such as athletic performance trends, learning curves, or market saturation.

All x values must be positive (you cannot take the logarithm of zero or negative numbers).

Internally, this transforms x to ln(x) and applies linear regression, so it leverages the same robust ordinary least squares implementation.

Compare with linear regression to see which fits better:

Stat::powerRegression( array $x, array $y )

Fit a power model y = a × x^b. Returns [a, b].

Power regression is useful for data following power law relationships (e.g., scaling laws, allometric relationships). Both x and y values must be positive.

Internally, this linearizes as ln(y) = ln(a) + b × ln(x) and applies linear regression.

Stat::exponentialRegression( array $x, array $y )

Fit an exponential model y = a × e^(b×x). Returns [a, b].

Exponential regression is useful for data with exponential growth (positive b) or decay (negative b), such as population growth, compound interest, or radioactive decay. All y values must be positive.

Internally, this linearizes as ln(y) = ln(a) + b × x and applies linear regression.

Stat::rSquared( array $x, array $y, bool $proportional = false, ?int $round = null )

Return the coefficient of determination (R²) — the proportion of variance in the dependent variable explained by the linear regression model. Values range from 0 (no explanatory power) to 1 (perfect fit).

Requires at least 2 data points and arrays of the same length.

With proportional regression (through the origin):

To compute R² for non-linear models, transform the data the same way the regression method does:

Stat::confidenceInterval( array $data, float $confidenceLevel = 0.95, ?int $round = null )

Return the confidence interval for the mean using the normal (z) distribution.

Computes: mean ± z * (stdev / √n), where the z-critical value is derived from the inverse normal CDF.

Requires at least 2 data points. The confidence level must be between 0 and 1 exclusive.

Stat::zTest( array $data, float $populationMean, Alternative $alternative = Alternative::TwoSided, ?int $round = null )

Perform a one-sample Z-test for the mean. Tests whether the sample mean differs significantly from a hypothesized population mean using the normal distribution.

Returns an associative array with zScore and pValue. The alternative hypothesis can be TwoSided (default), Greater, or Less.

Requires at least 2 data points.

Stat::tTest( array $data, float $populationMean, Alternative $alternative = Alternative::TwoSided, ?int $round = null )

Perform a one-sample t-test for the mean. Tests whether the sample mean differs significantly from a hypothesized population mean using the Student's t-distribution. Unlike the z-test, the t-test is appropriate for small samples where the population standard deviation is unknown.

Returns an associative array with tStatistic, pValue, and degreesOfFreedom. The alternative hypothesis can be TwoSided (default), Greater, or Less.

Requires at least 2 data points.

Stat::tTestTwoSample( array $data1, array $data2, Alternative $alternative = Alternative::TwoSided, ?int $round = null )

Perform a two-sample independent t-test (Welch's t-test). Compares the means of two independent groups without assuming equal variances. Uses the Welch–Satterthwaite approximation for degrees of freedom.

Returns an associative array with tStatistic, pValue, and degreesOfFreedom. The alternative hypothesis can be TwoSided (default), Greater, or Less.

Requires at least 2 data points in each sample.

Stat::tTestPaired( array $data1, array $data2, Alternative $alternative = Alternative::TwoSided, ?int $round = null )

Perform a paired t-test. Tests whether the mean difference between paired observations (e.g. before/after measurements on the same subjects) is significantly different from zero.

Returns an associative array with tStatistic, pValue, and degreesOfFreedom. Both arrays must have the same length.

Requires at least 2 paired observations.

Stat::chiSquaredTest( array $observed, ?array $expected = null, ?int $round = null )

Perform a chi-squared goodness-of-fit test. Use it when you want to check whether observed category counts differ from expected counts.

If $expected is omitted, a uniform distribution is assumed. Returns an associative array with chiSquared, pValue, and degreesOfFreedom.

Stat::chiSquaredIndependence( array $table, ?int $round = null )

Perform a chi-squared test of independence on a contingency table. Use it when you want to check whether two categorical variables are associated.

Returns an associative array with chiSquared, pValue, degreesOfFreedom, and the expected-count table.

Stat::kde ( array $data , float $h , KdeKernel $kernel = KdeKernel::Normal , bool $cumulative = false )

Create a continuous probability density function (or cumulative distribution function) from discrete sample data using Kernel Density Estimation. Returns a Closure that can be called with any point to estimate the density (or CDF value).

Supported kernels: KdeKernel::Normal (alias KdeKernel::Gauss), KdeKernel::Logistic, KdeKernel::Sigmoid, KdeKernel::Rectangular (alias KdeKernel::Uniform), KdeKernel::Triangular, KdeKernel::Parabolic (alias KdeKernel::Epanechnikov), KdeKernel::Quartic (alias KdeKernel::Biweight), KdeKernel::Triweight, KdeKernel::Cosine.

Using a different kernel:

Cumulative distribution function:

Stat::kdeRandom ( array $data , float $h , KdeKernel $kernel = KdeKernel::Normal , ?int $seed = null )

Generate random samples from a Kernel Density Estimate. Returns a Closure that, when called, produces a random float drawn from the KDE distribution defined by the data and bandwidth.

Supported kernels: KdeKernel::Normal (alias KdeKernel::Gauss), KdeKernel::Logistic, KdeKernel::Sigmoid, KdeKernel::Rectangular (alias KdeKernel::Uniform), KdeKernel::Triangular, KdeKernel::Parabolic (alias KdeKernel::Epanechnikov), KdeKernel::Quartic (alias KdeKernel::Biweight), KdeKernel::Triweight, KdeKernel::Cosine.

Using a different kernel:

Freq class

With Statistics package you can calculate frequency table. A frequency table lists the frequency of various outcomes in a sample. Each entry in the table contains the frequency or count of the occurrences of values within a particular group or interval.

Freq::frequencies( array $data )

You can see the frequency table as an array:

Freq::relativeFrequencies( array $data )

You can retrieve the frequency table in relative format (percentage):

You can see the frequency table as an array with percentage of the occurrences:

Freq::frequencyTableBySize( array $data , $size)

If you want to create a frequency table based on class (ranges of values) you can use frequencyTableBySize. The first parameter is the array, and the second one is the size of classes.

Calculate the frequency table with classes. Each group size is 4

Freq::frequencyTable()

If you want to create a frequency table based on class (ranges of values) you can use frequencyTable. The first parameter is the array, and the second one is the number of classes.

Calculate the frequency table with 5 classes.

Statistics class

The methods provided by the Freq and the Stat classes are mainly static methods. If you prefer to use an object instance for calculating statistics you can choose to use an instance of the Statistics class. So for calling the statistics methods, you can use your object instance of the Statistics class.

For example for calculating the mean, you can obtain the Statistics object via the make() static method, and then use the new object $stat like in the following example:

Calculate Frequency Table

The Statistics packages have some methods for generating Frequency Table:

NormalDist class

The NormalDist class provides an easy way to work with normal distributions in PHP. It allows you to calculate probabilities and densities for a given mean (μ\muμ) and standard deviation (σ\sigmaσ).

Key features


Class constructor


Methods

Properties: mean, sigma, and variance

You can access the distribution parameters via getter methods:

From samples:


Creating a normal distribution instance from sample data

The fromSamples() static method creates a normal distribution instance with mu and sigma parameters estimated from the sample data.

Example:

Generate random samples samples($n, $seed)

Generates $n random samples from the normal distribution using the Box-Muller transform. An optional $seed parameter allows reproducible results.


Z-score zscore($x)

Computes the standard score describing $x in terms of the number of standard deviations above or below the mean: (x - mu) / sigma.


Probability Density Function pdf($x)

Calculates the Probability Density Function at a given value xxx:

Example:


Cumulative Distribution Function cdf($x)

Calculates the Cumulative Distribution Function at a given value $x:

Example:

Calculating both, CDF and PDF:


Inverse Cumulative Distribution Function invCdf($p)

Computes the Inverse Cumulative Distribution Function (also known as the quantile function or percent-point function). Given a probability $p, it finds the value $x such that cdf($x) = $p.

Example:

The invCdf() method is useful for:

Round-trip example with cdf():


Quantiles quantiles($n)

Divides the normal distribution into $n continuous intervals with equal probability. Returns a list of $n - 1 cut points separating the intervals. Set $n to 4 for quartiles (the default), $n to 10 for deciles, or $n to 100 for percentiles.


Overlapping coefficient overlap($other)

Computes the overlapping coefficient (OVL) between two normal distributions. Measures the agreement between two normal probability distributions. Returns a value between 0.0 and 1.0 giving the overlapping area in the two underlying probability density functions.


Combining a normal distribution via add() method

The add() method allows you to combine a NormalDist instance with either a constant or another NormalDist object. This operation supports mathematical transformations and the combination of distributions.

The use cases are:

Scaling a normal distribution by a costant via multiply() method

The multiply() method for NormalDist multiplies both the mean (mu) and standard deviation (sigma) by a constant. This method is useful for rescaling distributions, such as when changing measurement units. The standard deviation is scaled by the absolute value of the constant to ensure it remains non-negative.

The method does not modify the existing object but instead returns a new NormalDist instance with the updated values.

Use Cases:

Subtracting from a normal distribution via subtract() method

The subtract() method is the counterpart to add(). It subtracts a constant or another NormalDist instance from this distribution.

Dividing a normal distribution by a constant via divide() method

The divide() method is the counterpart to multiply(). It divides both the mean (mu) and standard deviation (sigma) by a constant.


References for NormalDist

This class is inspired by Python’s statistics.NormalDist and aims to provide similar functionality for PHP users. (Work in Progress)

StudentT class

The StudentT class represents the Student’s t-distribution, which is used for hypothesis testing and confidence intervals when the population standard deviation is unknown, especially with small sample sizes. As the degrees of freedom increase, the t-distribution approaches the standard normal distribution.

Creating a StudentT instance

Probability Density Function (PDF)

Cumulative Distribution Function (CDF)

Inverse CDF (Quantile Function)

StreamingStat (Experimental)

Note: StreamingStat is experimental in version 1.x. It will be released as stable in version 2. If you want to provide feedback, we are happy to hear from you — please open an issue at https://github.com/Hi-Folks/statistics/issues.

StreamingStat computes descriptive statistics in a single pass with O(1) memory, ideal for large datasets or generator-based streams.

Method Description Min n
count() Number of values added 0
sum() Sum of all values 1
min() Minimum value 1
max() Maximum value 1
mean(?int $round = null) Arithmetic mean 1
variance(?int $round = null) Sample variance 2
pvariance(?int $round = null) Population variance 1
stdev(?int $round = null) Sample standard deviation 2
pstdev(?int $round = null) Population standard deviation 1
skewness(?int $round = null) Sample skewness (adjusted Fisher-Pearson) 3
pskewness(?int $round = null) Population skewness 3
kurtosis(?int $round = null) Excess kurtosis (sample) 4

All methods throw InvalidDataInputException when insufficient data is available.

Utility classes

The package includes utility classes under HiFolks\Statistics\Utils for common array and formatting operations.

Arr — array helpers

Arr::extract( array $data, array $columns )

Extract one or more columns from an array of associative arrays. Returns one array per requested column.

Arr::partition( array $data, string $field, string $operator, mixed $value )

Split an array of associative arrays into [$matching, $nonMatching] groups based on a condition. Supported operators: ==, !=, >, <, >=, <=.

Arr::toString( array $data, bool|int $sample = false )

Join array values into a comma-separated string. Pass an integer to limit to the first N values.

Arr::stripZeroes( array $data )

Remove zero values from the array.

Format — time formatting

Format::secondsToTime( int|float $seconds )

Convert seconds to a human-readable time string.

Format::timeToSeconds( string $time )

Parse a time string back to total seconds.

Format::secondsToHms( int|float $seconds )

Convert seconds to an associative array with hours, minutes, seconds keys.

Format::hmsToSeconds( int $hours, int $minutes, int $seconds )

Convert hours, minutes, and seconds to total seconds.

Testing

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security Vulnerabilities

Please review our security policy on how to report security vulnerabilities.

Credits

License

The MIT License (MIT). Please see License File for more information.


All versions of statistics with dependencies

PHP Build Version
Package Version
Requires php Version ^8.2|^8.3|^8.4|8.5
Composer command for our command line client (download client) This client runs in each environment. You don't need a specific PHP version etc. The first 20 API calls are free. Standard composer command

The package hi-folks/statistics contains the following files

Loading the files please wait ...