Array Creation
Complete reference for array creation methods and related utilities.
NDArray::array()
Create an NDArray from a PHP array.
public static function array(array $data,?DType $dtype = null): selfCreate arrays from PHP nested arrays.
Parameters:
array $data- PHP array containing data?DType $dtype- Optional data type. If null, inferred from data
Returns: NDArray with same shape as input array
Examples:
// 1D array
$arr = NDArray::array([1, 2, 3, 4, 5]);
echo implode(',', $arr->shape()); // 5
echo $arr->dtype()->name; // Float64
// 2D array
$matrix = NDArray::array([
[1, 2, 3],
[4, 5, 6]
]);
echo implode(',', $matrix->shape()); // 2,3
// 3D array
$tensor = NDArray::array([
[[1, 2], [3, 4]],
[[5, 6], [7, 8]]
]);
echo implode(',', $tensor->shape()); // 2,2,2
// With specific type
$int_arr = NDArray::array([1, 2, 3], DType::Int32);
echo $int_arr->dtype()->name; // Int32
// With mixed types (promoted to Float64)
$mixed = NDArray::array([1, 2.5, 3]);
echo $mixed->dtype()->name; // Float64Notes:
- All elements are converted to the specified or inferred type
- Nested arrays must have consistent dimensions
- Empty arrays are not allowed
See Also:
NDArray::zeros()
Create an array filled with zeros.
public static function zeros(array $shape, DType $dtype = DType::Float64): selfParameters:
array $shape- Array dimensions [rows, cols, ...]DType $dtype- Data type (default: Float64)
Examples:
// 1D
$zeros = NDArray::zeros([5]);
echo $zeros; // [0. 0. 0. 0. 0.]
// 2D
$zeros = NDArray::zeros([3, 3]);
echo $zeros;
// [[0. 0. 0.]
// [0. 0. 0.]
// [0. 0. 0.]]
// 3D
$zeros = NDArray::zeros([2, 3, 4]);
// With Int32 type
$zeros = NDArray::zeros([10], DType::Int32);See Also:
NDArray::ones()
Create an array filled with ones.
public static function ones(array $shape, DType $dtype = DType::Float64): selfParameters:
array $shape- Array dimensionsDType $dtype- Data type (default: Float64)
Examples:
$ones = NDArray::ones([2, 3]);
echo $ones;
// [[1. 1. 1.]
// [1. 1. 1.]]
// Useful for multiplicative operations
$data = NDArray::random([100, 100]);
$multiplier = NDArray::ones([100, 100])->multiply(2);NDArray::full()
Create an array filled with a specific value.
public static function full(
float|int|bool $value,
array $shape,
?DType $dtype = null
): selfParameters:
float|int|bool $value- Value to fill array witharray $shape- Array dimensions?DType $dtype- Data type (inferred from fillValue if null)
Examples:
// Fill with 5
$full = NDArray::full(5, [2, 2]);
echo $full;
// [[5. 5.]
// [5. 5.]]
// Fill with 3.14
$pi_matrix = NDArray::full(3.14, [3, 3]);
// With specific type
$full = NDArray::full(100, [10], DType::Int32);See Also:
NDArray::fromScalar()
Create a 0-dimensional (scalar) array from a single PHP value.
public static function fromScalar(
float|int|bool|Complex $value,
?DType $dtype = null
): selfThe resulting array has shape [] (empty shape) and contains the single value as its element. Use toScalar() to retrieve the value back, or let it broadcast naturally in element-wise operations.
Parameters:
float|int|bool|Complex $value- The scalar value?DType $dtype- Data type (inferred from value if null)
Examples:
$scalar = NDArray::fromScalar(42);
echo $scalar->shape(); // []
echo $scalar->toScalar(); // 42
echo $scalar->ndim(); // 0
// With explicit type
$floatScalar = NDArray::fromScalar(3.14, DType::Float32);
// Broadcasting works naturally
$ones = NDArray::ones([3, 4]);
$result = $ones->multiply(NDArray::fromScalar(5));
// All elements are now 5See Also:
- toScalar() — Extract value back to PHP scalar
NDArray::fromArray()
Create an NDArray from a PHP array with optional explicit shape.
public static function fromArray(
array $data,
?array $shape = null,
?DType $dtype = null
): selfThis is an idiomatic alias for array() that follows the naming convention of other factory methods like fromBuffer(), fromBytes(), etc. It provides an optional shape parameter for explicit control.
Parameters:
array $data- PHP array containing data?array $shape- Optional array shape. If null, inferred from data structure?DType $dtype- Optional data type. If null, inferred from data
Returns: NDArray with shape from parameter or inferred from data
Examples:
// Same as array() - shape inferred from nested structure
$arr = NDArray::fromArray([[1, 2], [3, 4]]);
echo implode(',', $arr->shape()); // 2,3
// With explicit shape validation
$data = [1, 2, 3, 4, 5, 6];
$arr = NDArray::fromArray($data, [2, 3]); // Validates data size matches shape
// With explicit dtype
$arr = NDArray::fromArray([1, 2, 3], null, DType::Float32);See Also:
- array() - Original method
- fromBuffer() - Create from C pointer
- fromBytes() - Create from binary string
NDArray::fromBuffer()
Create an array from an external C buffer pointer.
public static function fromBuffer(
CData $buffer,
array $shape,
DType $dtype
): selfCreates an NDArray by copying data from an external FFI buffer. The source buffer remains owned by the caller — this method creates an independent copy.
Parameters:
CData $buffer- Pointer to raw C data buffer (e.g.,float*,int16_t*)array $shape- Array shape dimensionsDType $dtype- Data type of the buffer elements
Returns: NDArray containing a copy of the buffer data
Throws:
ShapeException- If shape has zero or negative dimensions
Examples:
$sndfile = FFI::cdef("...", "libsndfile.dylib");
$buffer = $sndfile->sf_readf_float($file, $samples);
$audio = NDArray::fromBuffer($buffer, [44100, 2], DType::Float32);
$sndfile->free($buffer);Notes:
- Buffer must remain valid during the copy operation
- Returns a standard NDArray that can be used like any other
- No reference to original buffer is retained
WARNING: Low-Level Operation
This is a low-level FFI operation with no safety guards:
- Type must match exactly — Passing
DType::Float32with anint*buffer will read garbage values. No conversion is performed. - Size must match exactly — Buffer should contain exactly
array_product($shape)elements. Undefined behavior if size mismatches. - Buffer validity is your responsibility — Pass a dangling pointer and you'll get an undefined behavior.
Verify your buffer matches both the type and size before calling.
NDArray::fromBytes()
Create an array from a binary string.
public static function fromBytes(
string $bytes,
array $shape,
DType $dtype
): selfCreates an NDArray by interpreting a PHP binary string as raw array data. The bytes are copied into a new array with the specified shape and dtype. Data is assumed to be in little-endian format.
Parameters:
string $bytes- Binary string containing raw array dataarray $shape- Array shape dimensionsDType $dtype- Data type of the data in the string
Returns: NDArray containing a copy of the binary data
Throws:
ShapeException- If byte string length doesn't match expected size for the shape and dtype
Examples:
$binaryData = file_get_contents('data.bin');
$audio = NDArray::fromBytes($binaryData, [1000, 2], DType::Float32);
// Verify size matches
// 1000 * 2 * 4 bytes = 8000 bytes expected for Float32See Also:
- toBytes() — Export array to binary string
- fromBuffer() — Import from C pointer
NDArray::flat()
Get a 1-D iterator over the array.
public function flat(): FlatIteratorReturns a FlatIterator that provides 1-D access to the array elements in C-contiguous (row-major) order.
Returns: FlatIterator - Iterator over flattened array
Examples:
$matrix = NDArray::array([[1, 2], [3, 4]]);
// Iterate all elements
foreach ($matrix->flat() as $value) {
echo $value; // 1, 2, 3, 4
}
// Access by index
echo $matrix->flat()[0]; // 1
echo $matrix->flat()[3]; // 4
// Convert to PHP array
$flat = $matrix->flat()->toArray(); // [1, 2, 3, 4]
// Count elements
echo count($matrix->flat()); // 4Notes:
- Iterates in C-contiguous (row-major) order regardless of array layout
- Returns a snapshot - changes to the original array are not reflected
- For large arrays, prefer vectorized operations over iteration
See Also:
NDArray::eye()
Create an identity matrix.
public static function eye(
int $n,
?int $m = null,
int $k = 0,
DType $dtype = DType::Float64
): selfParameters:
int $n- Number of rows?int $m- Number of columns (defaults to $n)int $k- Index of diagonal (0=main, positive=upper, negative=lower)DType $dtype- Data type (default: Float64)
Examples:
// Square identity matrix
$eye = NDArray::eye(3);
echo $eye;
// [[1. 0. 0.]
// [0. 1. 0.]
// [0. 0. 1.]]
// Rectangular
$rect = NDArray::eye(3, 5);
echo $rect;
// [[1. 0. 0. 0. 0.]
// [0. 1. 0. 0. 0.]
// [0. 0. 1. 0. 0.]]
// Upper diagonal
$upper = NDArray::eye(3, k: 1);
echo $upper;
// [[0. 1. 0.]
// [0. 0. 1.]
// [0. 0. 0.]]
// Lower diagonal
$lower = NDArray::eye(3, k: -1);
echo $lower;
// [[0. 0. 0.]
// [1. 0. 0.]
// [0. 1. 0.]]See Also:
NDArray::arange()
Create evenly spaced values within a given interval.
public static function arange(
int|float $start,
int|float $stop = null,
int|float $step = 1,
?DType $dtype = null
): selfParameters:
int|float $start- Start value (inclusive)int|float $stop- Stop value (exclusive). If null, start becomes 0 and stop becomes startint|float $step- Spacing between values (default: 1)?DType $dtype- Data type (inferred if null)
Examples:
// 0 to 9
$arr = NDArray::arange(10);
echo $arr; // [0 1 2 3 4 5 6 7 8 9]
// 5 to 14
$arr = NDArray::arange(5, 15);
echo $arr; // [5 6 7 8 9 10 11 12 13 14]
// Even numbers
$evens = NDArray::arange(0, 10, 2);
echo $evens; // [0 2 4 6 8]
// Decrementing
$down = NDArray::arange(10, 0, -1);
echo $down; // [10 9 8 7 6 5 4 3 2 1]
// Float step
$floats = NDArray::arange(0, 1, 0.1);
echo $floats; // [0. 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9]See Also:
NDArray::meshgrid()
Create coordinate matrices from one-dimensional coordinate vectors.
public static function meshgrid(array $arrays, string $indexing = 'xy', bool $sparse = false): arrayGiven one or more coordinate vectors, meshgrid() returns one grid for each input. Dense grids are expanded to the full coordinate shape. Sparse grids keep singleton dimensions and avoid repeating coordinate values.
Parameters:
array $arrays- One-dimensional coordinate vectors. Each entry may be anNDArrayor a PHP array.string $indexing- Coordinate indexing mode:'xy'for Cartesian indexing or'ij'for matrix indexing. Default:'xy'.bool $sparse- Whether to return sparse grids. Default:false.
Returns: Array of NDArrays, one coordinate grid for each input vector. Each output keeps the dtype of its corresponding input vector.
Throws:
ShapeException- If no input arrays are provided.ShapeException- Ifindexingis not'xy'or'ij'.ShapeException- If any input is not one-dimensional.
Examples:
$x = NDArray::array([1, 2, 3]);
$y = NDArray::array([10, 20]);
[$xx, $yy] = NDArray::meshgrid([$x, $y]);
print_r($xx->shape());
// Output: [2, 3]
print_r($xx->toArray());
// Output: [[1, 2, 3], [1, 2, 3]]
print_r($yy->toArray());
// Output: [[10, 10, 10], [20, 20, 20]]Use matrix indexing when the first output axis should correspond to the first input vector:
[$xx, $yy] = NDArray::meshgrid([$x, $y], indexing: 'ij');
print_r($xx->shape());
// Output: [3, 2]
print_r($xx->toArray());
// Output: [[1, 1], [2, 2], [3, 3]]
print_r($yy->toArray());
// Output: [[10, 20], [10, 20], [10, 20]]Sparse grids keep only the dimensions needed for each coordinate vector:
[$xx, $yy] = NDArray::meshgrid([$x, $y], sparse: true);
print_r($xx->shape());
// Output: [1, 3]
print_r($yy->shape());
// Output: [2, 1]See Also:
NDArray::linspace()
Create linearly spaced values.
public static function linspace(
float $start,
float $stop,
int $num = 50,
bool $endpoint = true,
?DType $dtype = null
): selfParameters:
float $start- Starting valuefloat $stop- Ending valueint $num- Number of samples (default: 50)bool $endpoint- Include stop value (default: true)?DType $dtype- Data type (default: Float64)
Examples:
// 5 values from 0 to 1
$arr = NDArray::linspace(0, 1, 5);
echo $arr; // [0. 0.25 0.5 0.75 1.]
// Exclude endpoint
$arr = NDArray::linspace(0, 1, 5, endpoint: false);
echo $arr; // [0. 0.2 0.4 0.6 0.8]
// Create time points
$time = NDArray::linspace(0, 10, 1000);Difference from arange():
arange()uses step size, excludes stoplinspace()uses number of points, includes stop by default
NDArray::logspace()
Create logarithmically spaced values.
public static function logspace(
float $start,
float $stop,
int $num = 50,
float $base = 10.0,
?DType $dtype = null
): selfParameters:
float $start- Start exponent (base**start)float $stop- Stop exponent (base**stop)int $num- Number of samples (default: 50)float $base- Base of log space (default: 10.0)?DType $dtype- Data type (default: Float64)
Examples:
// 10^0 to 10^2
$arr = NDArray::logspace(0, 2, 5);
echo $arr; // [1. 3.162 10. 31.623 100.]
// Base 2
$powers = NDArray::logspace(0, 10, 11, base: 2);
echo $powers; // [1. 2. 4. 8. 16. 32. 64. 128. 256. 512. 1024.]NDArray::geomspace()
Create geometrically spaced values.
public static function geomspace(
float $start,
float $stop,
int $num = 50,
?DType $dtype = null
): selfParameters:
float $start- Starting valuefloat $stop- Ending valueint $num- Number of samples (default: 50)?DType $dtype- Data type (default: Float64)
Examples:
// Geometric progression from 1 to 1000
$arr = NDArray::geomspace(1, 1000, 4);
echo $arr; // [1. 10. 100. 1000.]NDArray::random()
Create array with uniform random values in [0, 1).
public static function random(
array $shape,
DType $dtype = DType::Float64
): selfExamples:
$random = NDArray::random([3, 3]);
echo $random;
// [[0.234 0.891 0.456]
// [0.123 0.678 0.901]
// [0.567 0.345 0.789]]
// Float32 for ML
$weights = NDArray::random([784, 256], DType::Float32);NDArray::randn()
Create array with standard normal distribution (mean=0, std=1).
public static function randn(
array $shape,
DType $dtype = DType::Float64
): selfExamples:
$normal = NDArray::randn([1000]);
$mean = $normal->mean(); // ~0
$std = $normal->std(); // ~1NDArray::normal()
Create array with normal distribution.
public static function normal(
float $mean,
float $std,
array $shape,
DType $dtype = DType::Float64
): selfExamples:
// Mean=10, Std=2
$dist = NDArray::normal(10, 2, [1000]);
echo $dist->mean(); // ~10
echo $dist->std(); // ~2NDArray::uniform()
Create array with uniform distribution in [low, high).
public static function uniform(
float $low,
float $high,
array $shape,
DType $dtype = DType::Float64
): selfExamples:
// Values between -1 and 1
$uniform = NDArray::uniform(-1, 1, [100]);NDArray::randomInt()
Create array with random integers.
public static function randomInt(
int $low,
int $high,
array $shape,
DType $dtype = DType::Int64
): selfParameters:
int $low- Lower bound (inclusive)int $high- Upper bound (exclusive)array $shape- Array dimensionsDType $dtype- Integer type (default: Int64)
Examples:
// Random integers 0-99
$ints = NDArray::randomInt(0, 100, [1000]);
// Dice rolls
$dice = NDArray::randomInt(1, 7, [100]); // 1-6
// For images (0-255)
$pixels = NDArray::randomInt(0, 256, [224, 224, 3], DType::UInt8);copy()
Create a deep copy of the array.
public function copy(): selfThe returned array is always C-contiguous and owns its data. Modifying the copy does not affect the original.
Parameters
No parameters.
Returns
NDArray- Independent copy with new memory.
Examples
$original = NDArray::array([1, 2, 3]);
$copy = $original->copy();
// Modifying copy doesn't affect original
$copy->set([0], 999);
echo $original->get(0); // 1 (unchanged)astype()
Convert array to a different data type.
public function astype(DType $dtype): selfReturns a new array with the specified dtype. If the target dtype is the same as the current dtype, this is equivalent to copy().
Parameters
| Name | Type | Description |
|---|---|---|
$dtype | DType | Target data type |
Returns
NDArray- New array with converted data (same shape).
Examples
$floats = NDArray::array([1.5, 2.7, 3.2]);
$ints = $floats->astype(DType::Int32);
print_r($ints->toArray()); // [1, 2, 3]cast()
Cast array to a different dtype, without copy when already the target type.
public function cast(DType $dtype): selfUnlike astype() which always creates a new copy, this method returns the same array instance (zero-cost) when the current dtype already matches the requested one. Only when an actual type conversion is needed does it delegate to astype() and allocate new memory.
Parameters
| Name | Type | Description |
|---|---|---|
$dtype | DType | Target data type |
Returns
NDArray- Array in the target dtype (may be the same instance).
Examples
$arr = NDArray::array([1, 2, 3], DType::Int64);
$same = $arr->cast(DType::Int64); // No copy, same instance
$converted = $arr->cast(DType::Float64); // Copy, dtype differsSummary Table
| Method | Purpose | Use Case |
|---|---|---|
array() | From PHP array | Import existing data |
zeros() | Filled with zeros | Initialization |
ones() | Filled with ones | Multiplicative identity |
full() | Filled with value | Specific constant |
empty() | Uninitialized | Pre-allocation (must fill) |
zerosLike() | Zeros like input | Same shape as array |
onesLike() | Ones like input | Same shape as array |
fullLike() | Filled like input | Same shape as array |
fromArray() | From PHP array (with shape) | Import with explicit shape |
fromScalar() | 0-dimensional from value | Broadcasting, scalar-in-array context |
fromBuffer() | From C pointer | FFI interoperability |
fromBytes() | From binary string | File I/O, network data |
eye() | Identity matrix | Linear algebra |
arange() | Evenly spaced | Integer sequences |
linspace() | Linear spacing | Continuous ranges |
logspace() | Logarithmic spacing | Exponential ranges |
geomspace() | Geometric spacing | Multiplicative sequences |
random() | Uniform [0,1) | General random |
randn() | Standard normal | Statistical data |
normal() | Custom normal | Statistical distributions |
uniform() | Uniform range | Bounded random |
randomInt() | Random integers | Discrete random |
copy() | Deep copy | Independent array from existing |
astype() | Type conversion | New array with different dtype |
cast() | Conditional type conversion | Same instance if dtype matches, copy otherwise |
