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.
key()doesn't work like that. If you're just trying to access the keys of the array, just make use of$kprovided by yourforeachconstruct. 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 */ }.