Numeric vector with element-wise arithmetic, dot and cross products, and array-style access.
The Vector class provides a general-purpose numeric vector with support for:
- Element-wise arithmetic (addition, subtraction, scalar multiplication, scalar division)
- Dot product and cross product operations
- Exact and approximate equality comparison
- Conversion to arrays and matrices
- Array-style element access via the
ArrayAccessinterface
Vectors are directionless (neither row nor column). When converted to a Matrix, a vector is treated as a column vector by default.
Size-0 vectors are allowed.
public float $magnitude { get; }The magnitude (Euclidean norm) of the vector, computed on every access.
For v = (x₁, x₂, ..., xₙ): ‖v‖ = √(x₁² + x₂² + ... + xₙ²)
public int $size { get; }The number of elements in the vector.
public function __construct(int $size)Create a new vector with the specified number of elements, all initialised to zero.
Parameters:
$size(int) - Number of elements.
Throws:
DomainExceptionif size is negative.
Examples:
$v1 = new Vector(3); // [0.0, 0.0, 0.0]
$v2 = new Vector(0); // [] (empty vector)public static function fromArray(array $arr): selfCreate a vector from an array of numbers. Integer values are cast to float. Array keys are ignored; values are re-indexed from zero.
Parameters:
$arr(array<array-key, int|float>) - Array of numbers.
Returns:
self- A new vector containing the array values.
Throws:
InvalidArgumentExceptionif any element is not a number.
Examples:
$v1 = Vector::fromArray([1, 2, 3]);
$v2 = Vector::fromArray([3.14, -1, 0]);
$v3 = Vector::fromArray([]); // Size-0 vectorpublic function get(int $index): floatGet a vector element by index.
Parameters:
$index(int) - Element index (0-based).
Returns:
float- Value of the vector element.
Throws:
OutOfRangeExceptionif the index is outside the valid range.
Examples:
$v = Vector::fromArray([10, 20, 30]);
echo $v->get(0); // 10.0
echo $v->get(2); // 30.0public function set(int $index, int|float $value): voidSet a vector element by index. Integer values are cast to float.
Parameters:
$index(int) - Element index (0-based).$value(int|float) - Value to set.
Throws:
OutOfRangeExceptionif the index is outside the valid range.
Examples:
$v = Vector::fromArray([1, 2, 3]);
$v->set(1, 99);
echo $v->get(1); // 99.0The equal() and approxEqual() methods are provided by the ApproxEquatable trait from the Core package.
public function equal(mixed $other): boolCheck if this vector exactly equals another value.
Two vectors are equal if they have the same size and all corresponding elements are exactly equal. Returns false for non-Vector values.
Parameters:
$other(mixed) - The value to compare with.
Returns:
bool- True if the vectors are the same size and all elements are exactly equal.
Examples:
$v1 = Vector::fromArray([1, 2, 3]);
$v2 = Vector::fromArray([1, 2, 3]);
$v3 = Vector::fromArray([1.0000000001, 2, 3]);
var_dump($v1->equal($v2)); // true (exact match)
var_dump($v1->equal($v3)); // false (not exact)
// Invalid types return false
var_dump($v1->equal('string')); // false
var_dump($v1->equal(null)); // falsepublic function approxEqual(
mixed $other,
float $relTol = Floats::DEFAULT_RELATIVE_TOLERANCE,
float $absTol = Floats::DEFAULT_ABSOLUTE_TOLERANCE
): boolCheck if this vector approximately equals another value within specified tolerances.
Each pair of corresponding elements is compared using Floats::approxEqual(), which checks absolute tolerance first, then relative tolerance. Returns false for non-Vector values.
Parameters:
$other(mixed) - The value to compare with.$relTol(float) - Relative tolerance (default: 1e-9).$absTol(float) - Absolute tolerance (default: PHP_FLOAT_EPSILON).
Returns:
bool- True if the vectors are the same size and all elements are approximately equal.
Throws:
DomainExceptionif either tolerance is negative.
Examples:
$v1 = Vector::fromArray([1, 2, 3]);
$v2 = Vector::fromArray([1.00000001, 2.00000001, 3.00000001]);
// Within default tolerance
var_dump($v1->approxEqual($v2)); // true
// With tight tolerance
var_dump($v1->approxEqual($v2, 1e-15, 1e-15)); // false
// Invalid types return false
var_dump($v1->approxEqual('string')); // falsepublic function neg(): selfNegate this vector. Returns a new vector with all elements negated.
Example:
$v = Vector::fromArray([1, -2, 3]);
$result = $v->neg(); // [-1, 2, -3]public function add(self $other): selfAdd another vector to this one, element by element.
Parameters:
$other(Vector) - Vector to add.
Returns:
self- New vector representing the sum.
Throws:
LengthExceptionif vectors have different sizes.
Examples:
$v1 = Vector::fromArray([1, 2, 3]);
$v2 = Vector::fromArray([4, 5, 6]);
$sum = $v1->add($v2); // [5, 7, 9]public function sub(self $other): selfSubtract another vector from this one, element by element.
Parameters:
$other(Vector) - Vector to subtract.
Returns:
self- New vector representing the difference.
Throws:
LengthExceptionif vectors have different sizes.
Examples:
$v1 = Vector::fromArray([5, 7, 9]);
$v2 = Vector::fromArray([1, 2, 3]);
$diff = $v1->sub($v2); // [4, 5, 6]public function mul(int|float $scalar): selfMultiply this vector by a scalar.
Parameters:
$scalar(int|float) - Number to multiply by.
Returns:
self- New vector representing the product.
Examples:
$v = Vector::fromArray([1, 2, 3]);
$result = $v->mul(3); // [3, 6, 9]public function div(int|float $scalar): selfDivide this vector by a scalar.
Parameters:
$scalar(int|float) - Number to divide by.
Returns:
self- New vector representing the quotient.
Throws:
DivisionByZeroErrorif scalar is zero.
Examples:
$v = Vector::fromArray([6, 9, 12]);
$result = $v->div(3); // [2, 3, 4]public function dot(self $other): floatCalculate the dot product of this vector with another vector.
Parameters:
$other(Vector) - Vector to calculate dot product with.
Returns:
float- The dot product.
Throws:
LengthExceptionif vectors have different sizes.
Examples:
$v1 = Vector::fromArray([1, 2, 3]);
$v2 = Vector::fromArray([4, 5, 6]);
$result = $v1->dot($v2); // 32.0 (1*4 + 2*5 + 3*6)public function cross(self $other): selfCalculate the cross product of this vector with another vector. Both vectors must be size 3.
Parameters:
$other(Vector) - Vector to calculate cross product with.
Returns:
self- New vector representing the cross product.
Throws:
LengthExceptionif either vector is not size 3.
Examples:
$v1 = Vector::fromArray([1, 0, 0]);
$v2 = Vector::fromArray([0, 1, 0]);
$result = $v1->cross($v2); // [0, 0, 1]public function normalize(): selfNormalize this vector to a unit vector (magnitude 1). The result has the same direction as the original.
Returns:
self- A new vector with magnitude 1.
Throws:
DivisionByZeroErrorif the vector has zero magnitude.
Examples:
$v = Vector::fromArray([3, 4]);
$unit = $v->normalize();
echo $unit->magnitude; // 1.0
echo $unit->get(0); // 0.6
echo $unit->get(1); // 0.8public function toArray(): arrayGet a copy of the vector data as an array.
Returns:
list<float>- Array of vector elements.
Examples:
$v = Vector::fromArray([1, 2, 3]);
$array = $v->toArray(); // [1.0, 2.0, 3.0]public function toMatrix(bool $asRow = false): MatrixConvert this vector to a Matrix.
By default, returns an n x 1 column matrix. If $asRow is true, returns a 1 x n row matrix.
Parameters:
$asRow(bool) - If true, return a 1 x n row matrix; if false (default), return an n x 1 column matrix.
Returns:
Matrix- The matrix representation.
Examples:
$v = Vector::fromArray([1, 2, 3]);
// Column matrix (default)
$col = $v->toMatrix();
// [[1],
// [2],
// [3]]
// Row matrix
$row = $v->toMatrix(true);
// [[1, 2, 3]]public function format(bool $asRow = false): stringFormat the vector as a string using box-drawing characters.
Parameters:
$asRow(bool) - If true, format as a row vector; if false (default), format as a column vector.
Returns:
string- The formatted string.
Examples:
$v = Vector::fromArray([1, 2, 3]);
echo $v->format();
// ┌ ┐
// │ 1.0 │
// │ 2.0 │
// │ 3.0 │
// └ ┘
echo $v->format(true);
// ┌ ┐
// │ 1.0 2.0 3.0 │
// └ ┘public function __toString(): stringConvert the vector to a string representation. Delegates to format(), rendering as a column vector by default.
Examples:
$v = Vector::fromArray([1, 2, 3]);
echo $v;
// ┌ ┐
// │ 1.0 │
// │ 2.0 │
// │ 3.0 │
// └ ┘Vectors can be accessed using bracket syntax:
$v = Vector::fromArray([1, 2, 3]);
// Read access
echo $v[0]; // 1
echo $v[1]; // 2
echo $v[2]; // 3
// Write access
$v[0] = 10;
echo $v[0]; // 10
// Check existence
var_dump(isset($v[0])); // true
var_dump(isset($v[5])); // false
// Cannot unset elements
unset($v[0]); // Throws LogicExceptionpublic function offsetExists(mixed $offset): boolCheck if an offset exists. Returns true if the offset is an integer within the valid range.
Parameters:
$offset(mixed) - Index to check.
Returns:
bool- True if the offset is valid.
public function offsetGet(mixed $offset): floatGet value at an offset.
Parameters:
$offset(mixed) - Index to get.
Returns:
float- The value at the given index.
Throws:
OutOfRangeExceptionif offset is out of bounds.
public function offsetSet(mixed $offset, mixed $value): voidSet value at an offset.
Parameters:
$offset(mixed) - Index to set.$value(mixed) - Value to set.
Throws:
OutOfRangeExceptionif offset is outside valid range.InvalidArgumentExceptionif value is not a number.
public function offsetUnset(mixed $offset): voidUnsetting elements is not supported.
Throws:
LogicException- Always throws.