05-17-2011, 06:28 PM
I have 3 categories: Small box, Medium box, and Large box. Each have the length, width and depth listed. I need to get the volume for each box size. I think I understand how to initialize an associative multidimensional array. I understand how to multiply. I don't understand how to multiply and make a statement for each box's volume. I think it has something to do with a foreach statement but I'm stuck. Please help!!
05-17-2011, 06:44 PM
Multiplying it can be done with an iteration. IMO, useless in PHP unless you need to recurse it.
PHP has a function for this called array_product. It works on a single level, but that's not really an issue either.
$aCalcs = array();
foreach ($yourArrayHere AS $key => $value)
$aCalcs[$key] = array_product($value);
Its not a recursive function, so you'll need to specify which level to work with. It shouldn't care if its associative or not, it will only focus on the (float)$values.
For a more advanced feature, you could use a class for this as well:
public function __construct($sBoxName, $x, $y, $z)
$this->sBoxName = $sBoxName;
$this->x = $x;
$this->y = $y;
$this->z = $z;
// You'd have getters/setters to access / mutate the data here, but I won't add those
public function getVolume()
return $this->x * $this->y * $this->z;
$aBoxes = array(
new Box('Small Box', 1, 1, 1),
new Box('Medium Box', 2, 2, 2),
new Box('Large Box', 3, 3, 3)
foreach ($aBoxes AS $box)
// getName would be one of the accessors which I skipped
print $box->getName() . ' has ' . $box->getVolume() . ' volume available';