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
);
if (false !== array_search('28', $terms)) {
unset($terms[array_search('28', $terms)]);
}
You can use array_keys to find all indexs of the needle.
<?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)]);
}
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
}