Jump to content

Removing empty array after unset with for and echo


saynotojava
Go to solution Solved by PaperTiger,

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.

Link to comment
Share on other sites

  • Solution

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 />";
 
}
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.