This is what I am trying to do. I would like my code to return the following:
"The volume of the small box is: 300"
But I cannot seem to figure out what to do:
<?php
$box = array(
"Small box" => array("length" => 12, "width" => 10, "depth" => 2.5),
"Medium box" => array("length" => 30, "width" => 20, "depth" => 4),
"Large box" => array("length" => 60, "width" => 40, "depth" => 11.5)
);
foreach ($box as $number => $boxes)
{
echo "The volume of the "."$number"." is: \t";
foreach ($boxes as $value)
{
if (is_numeric($value))
{
$sum = array_product($boxes);
echo "$sum";
}
}
echo "<br />";
}
?>
You are looping through the $value
, calculating and displaying the $sum
multiple (3) times. Just calculate the product:
foreach ($box as $number => $boxes)
{
echo "The volume of the "."$number"." is: \t";
echo array_product($boxes);
echo "<br />";
}
If you don't have a predictable array with length
, width
and depth
then there is little point in doing this at all, but you could also do:
echo $boxes['length'] * $boxes['width'] * $boxes['depth'];
$box = array(
"Small box" => array("length" => 12, "width" => 10, "depth" => 2.5),
"Medium box" => array("length" => 30, "width" => 20, "depth" => 4),
"Large box" => array("length" => 60, "width" => 40, "depth" => 11.5)
);
foreach ($box as $key => $boxes) {
$volume = array_product($boxes);
echo "The volume of the $key is: $volume
";
}
you can get size of box into index array
$sum = 1;/*set variable sum to 1 so if it's * in another numerics it's not 0*/
$i = 0; /*set i condition to reset value of condition*/
foreach ($box as $number => $boxes) {
foreach ($boxes as $value)
{
if (is_numeric($value)){
$sum = $sum*$value; /*it's product length*width*depth */
}
/*cek the condition if count of boxes is limit lengt so define variable data["box type"]*/
if(($i+1) == count($boxes)){
$data[$number] = $sum; /*give value for $data["box type"]*/
}
$i++;
}
$sum = 1;/*reset sum to 1*/
$i =0;/*reset i to 0*/
}
this the result of print_r($data);
Array
(
[Small box] => 300
[Medium box] => 2400
[Large box] => 27600
)
and you can access the variable to any type of box using.
echo "sample : The volume of the Medium Box is ". $data["Medium box"]." : \t";
and the result will be like
sample : The volume of the Medium Box is 2400
let me know if this you looking for.