You don’t need the loop at all if you have only one item
and one price
in your array:
$item= "stackoverflow";
$price = "30.00";
$cs1_array = array();
$cs1_array['item'] = $item;
$cs1_array['price'] = $price;
if(sizeof($cs1_array) > 0){
echo "<table>";
echo "<tr>";
echo "<td>{$cs1_array['item']}</td><td>{$cs1_array['price']}</td>";
echo "</tr>";
echo "</table>";
}
However, if you’d like to have multiple instances of item
and price
, you need an array of arrays:
$cs1_array = array();
$cs1_array[] = array(
"item" => "stackoverflow",
"price" => "30.00"
);
$cs1_array[] = array(
"item" => "superuser",
"price" => "40.00"
);
$cs1_array[] = array(
"item" => "serverfault",
"price" => "20.00"
);
// and so on
As a more concise alternative to the above code, you may create the array and fill it with values in a single statement:
$cs1_array = array(
array(
"item" => "stackoverflow",
"price" => "30.00"
),
array(
"item" => "superuser",
"price" => "40.00"
),
array(
"item" => "serverfault",
"price" => "20.00"
),
// and so on
);
Then the foreach
loop will work correctly:
if(sizeof($cs1_array) > 0){
echo "<table>";
foreach($cs1_array as $item){
echo "<tr>";
echo "<td>{$item['item']}</td><td>{$item['price']}</td>";
echo "</tr>";
}
echo "</table>";
}