Jump to content

Removing empty array after unset with for and echo


saynotojava

Recommended Posts

I have following two dimensional array:

$shop = array( array( Title => "rose",
                      Price => 1.25,
                      Number => 15
                    ),
               array( Title => "daisy",
                      Price => 0.75,
                      Number => 25,
                    ),
               array( Title => "orchid",
                      Price => 1.15,
                      Number => 7
                    )
             );

Where i want to unset/remove one array in it,i do that with following:

$count=3;

unset ($shop[0]);

And i output array after that with this:

for ($row = 0; $row < $count; $row++)
{
    echo $shop[$row]["Title"]." costs ".$shop[$row]["Price"]." and you get ".$shop[$row]["Number"];
    echo "<br />";

}
 

The problem is how with unset array is not fully removed,it just show as empty value,so while it should output array like this:

daisy costs 0.75 and you get 25
orchid costs 1.15 and you get 7

It shows this:

costs and you get
daisy costs 0.75 and you get 25
orchid costs 1.15 and you get 7

And if i output array with print_r,then it shows properly but i need it with echo format.

Because you set the count as 3 before you unset the first element, so it will always loop through 3 times.

 

You don't really need the count at all. You can just do:

 

 

unset ($shop[0]);
foreach($shop as $item)
{
    echo $item["Title"]." costs ".$item["Price"]." and you get ".$item["Number"];
    echo "<br />";
 
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.