1

I have inserted some elements (fruit names) queried from mySQL into an array. Now, I would like to remove certain items from the array. I want to remove 'Apple' and 'Orange' if the exist from the array. This is what I tried but I am getting an error message.

Array Example:
Array ( [1] => Orange [2] => Apple)

foreach($terms as $k => $v) 
{
    if (key($v) == "Apple") 
    {
        unset($terms[$k]);
    }
    elseif( key($v) == "Orange")
    {
        unset($terms[$k]);
    }

}


>>> Warning: key() expects parameter 1 to be array, string given //same error repeated 4 times

I referred to this link here: How do you remove an array element in a foreach loop? I would be grateful if anyone can point out what I did wrong.

Community
  • 1
  • 1
Cryssie
  • 3,047
  • 10
  • 54
  • 81
  • `key()` doesn't work like that. If you're just trying to access the keys of the array, just make use of `$k` provided by your `foreach` construct. In this case, **your array is not associative**, so your keys are numeric and therefore it won't work. Solution would be to either change your array to be associative (eg: `$arr = ['foo' => 'hello', 'bar' => 'howdy'];`), or change the comparison like so: `if ($v == 'SomeValue') { /* do stuff */ }`. – Amal Murali Apr 22 '14 at 06:28
  • @AmalMurali Thanks for the explanation. I just started php not long ago and still learning from examples. – Cryssie Apr 22 '14 at 06:30

2 Answers2

5

Have you tried it this way:

foreach($terms as $k => $v) 
{ 
    if ($v == "Apple") 
    {
        unset($terms[$k]);
    }
    elseif($v == "Orange")
    {
        unset($terms[$k]);
    }

}
Abed Hawa
  • 1,372
  • 7
  • 18
  • While the selected answer is more structurally sound this is a good answer for highlighting the actual current value in the foreach loop ($v) – Pogrindis Apr 22 '14 at 07:04
1

Explanation:

The $fr is your actual array of all fruits.. and your $rm is another array that contains list of items to be removed from your $fr array.

Using a foreach cycle through the $rm array and see if the element exists on the $fr array , if found, unset() it.

The code...

<?php
$fr = array('Apple','Orange','Pineapple'); //<-- Your actual array
$rm = array('Apple','Orange'); //<--- Elements to be removed 

foreach($rm as $v)
{
    if(in_array($v,$fr))
    {
        unset($fr[array_search($v,$fr)]);
    }
}
print_r($fr);

OUTPUT :

Array
(
    [2] => Pineapple
)

Using array_diff()

print_r(array_diff($fr,$rm));

Code Demonstration

Shankar Narayana Damodaran
  • 68,075
  • 43
  • 96
  • 126