Search code examples
phparraysunset

Remove an array element in indexed array using key


If I have a value '28' and I want to search through an array for the index that contains that value and remove it. Is there a way without running a for loop through each element in the array?

In this case I would want to remove the element $terms[7] or 6 => 28

$needle = 28;
$terms = array(
  0 =>  42
  1 =>  26
  2 =>  27
  3 =>  43
  4 =>  21
  5 =>  45
  6 =>  28
  7 =>  29
  8 =>  30
  9 =>  31
  10 =>  46
);

Solution

  • if (false !== array_search('28', $terms)) {
          unset($terms[array_search('28', $terms)]);
    }