1

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
);
2
  • This is a little tricky based on your programs needs. Can 28 appear multiple times? does it need to unset all instances of your search term or just the first one found? Long and short of it is either way you will need to use a loop on an unsorted array, with some slight efficiency improvements based on functional requirements that can be made. Commented May 26, 2017 at 22:54
  • @ Patrick - It will only appear once in the array. The number 28 represents the current page term / category you are viewing. Thanks Commented May 26, 2017 at 23:15

3 Answers 3

4
if (false !== array_search('28', $terms)) {
      unset($terms[array_search('28', $terms)]);
}
Sign up to request clarification or add additional context in comments.

Comments

2

As mentioned above, use array_search() to find the item. Then, use unset() to remove it from the array.

$haystack = [42, 28, 27, 45];
$needle = 28;

$index = array_search($needle, $haystack);

if ($index !== false) {
    unset($haystack[$index]);
} else {
    // $needle not present in the $haystack
}

Comments

1

You can use array_keys to find all indexs of the needle.

array_keys

<?php
    $needle = 28;
    $haystack = [42, 26, 27, 43, 21, 45, 28, 29, 30, 31, 28, 46];
    $results = array_keys($haystack, $needle, true);
    while (!empty($results)) {
      unset($haystack[array_shift($results)]);
    }

2 Comments

If you just want to point the OP to a function then its a comment and not an answer. If you want to write some code along with an explanation it becomes an answer the OP and other can understand and make use of now and when other see the answer
Point taken. I've added an example that resolves the issue with multiple matches.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.