beans
beans

Reputation: 1765

PHP, remove from array?

Im searching through an array of countries to see if any match the UK, if so I pull it out and put it at the top of my drop down.

foreach($this->registry->stockistCountries as $value)
{
    if($value['country'] == 'UK'){
        $buffer .= '<option>UK</option>';
        $buffer .= '<option disabled>------------------</option>';
    }

}

I was wondering, if UK is found, is there a way to remove it from the array $this->registry->stockistCountries?

Thanks

Upvotes: 2

Views: 615

Answers (4)

nithi
nithi

Reputation: 3887

$found = array_search('UK', $this->registry->stockistCountries); //search for UK


unset($this->registry->stockistCountries[$found]); // Remove from array

Upvotes: 0

Vasisualiy
Vasisualiy

Reputation: 750

Something like @unset($this->registry->stocklist['country']['UK']);

Upvotes: 0

Rawkode
Rawkode

Reputation: 22592

Change your loop to:

foreach($this->registry->stockistCountries as $i => $value)
{
    if($value['country'] == 'UK'){
        $buffer .= '<option>UK</option>';
        $buffer .= '<option disabled>------------------</option>';
        unset($this->registry->stockistCountries[$i]);
    }

}

Upvotes: 3

oezi
oezi

Reputation: 51807

just change your foreach-loop to also get the key and then just use unset():

foreach($this->registry->stockistCountries as $key => $value){
                                  // add this ^^^^^^^^
  // do something
  if(/* whatever */){
    unset($this->registry->stockistCountries[$key]);
  }
}

Upvotes: 1

Related Questions