# A Lattice class

Consider if you need a 7-dimensional lattice data structure. An array is great for one-dimensional data but once you add dimensions things quickly get difficult to manage. Here’s a data structure that takes away some of that headache:

```<?php

class Lattice {

private \$lattice = null;
private \$dimensions = 0;
private \$boundaries = null;

public function setDimensions(\$d) {
if (is_integer(\$d)) {
\$this->dimensions = \$d;
} else {
throw new Exception('setDimensions expects an integer. given: ' . \$d);
}
}
public function getDimensions() {
return \$this->dimensions;
}
public function setBoundaries(array \$boundaries) {
\$iteration = count(\$boundaries);
if (\$this->dimensions > 0 && \$this->dimensions == count(\$boundaries)) {
\$this->boundaries = \$boundaries;
\$array = null;
while (\$iteration > 0) {
\$iteration --;
\$array = array_fill(0, \$boundaries[\$iteration], \$array);
}
\$this->lattice = \$array;
} else {
throw new Exception("Boundary count should match dimension count");
}
}
public function setNode(array \$coordinates, \$value) {
if (count(\$coordinates) != \$this->dimensions) {
throw new Exception("Passed coordinates have dimension mismatch");
}
\$iteration = 0;
\$array = &\$this->lattice;
while (\$iteration < count(\$coordinates) - 1) {
\$coordinate = \$coordinates[\$iteration];

if (\$coordinate > \$this->boundaries[\$iteration] - 1) {
throw new Exception("coordinate \$iteration is out of bounds");
}
\$array = &\$array[\$coordinate];
\$iteration++;
}
\$coordinate = \$coordinates[\$iteration];
if (\$coordinate > \$this->boundaries[\$iteration] - 1) {
throw new Exception("coordinate \$iteration is out of bounds");
}
\$array[\$coordinate] = \$value;
}
public function getNode(array \$coordinates) {
if (count(\$coordinates) != \$this->dimensions) {
throw new Exception("Passed coordinates have dimension mismatch");
}
\$iteration = 0;
\$array = &\$this->lattice;
while (\$iteration < count(\$coordinates) - 1) {
\$coordinate = \$coordinates[\$iteration];

if (\$coordinate > \$this->boundaries[\$iteration] - 1) {
throw new Exception("coordinate \$iteration is out of bounds");
}
\$array = &\$array[\$coordinate];
\$iteration++;
}
\$coordinate = \$coordinates[\$iteration];
if (\$coordinate > \$this->boundaries[\$iteration] - 1) {
throw new Exception("coordinate \$iteration is out of bounds");
}
return \$array[\$coordinate];
}
public function toArray() {
return \$this->lattice;
}
}

```