23

Is it possible to remove a string (see example below) from a PHP array without knowing the index?

Example:

array = array("string1", "string2", "string3", "string4", "string5");

I need to remove string3.

cherouvim
  • 31,725
  • 15
  • 104
  • 153
Zac Brown
  • 5,905
  • 19
  • 59
  • 107

6 Answers6

44
$index = array_search('string3',$array);
if($index !== FALSE){
    unset($array[$index]);
}

if you think your value will be in there more than once try using array_keys with a search value to get all of the indexes. You'll probably want to make sure

EDIT:

Note, that indexes remain unchanged when using unset. If this is an issue, there is a nice answer here that shows how to do this using array_splice.

Community
  • 1
  • 1
GWW
  • 43,129
  • 11
  • 115
  • 108
7

This is probably not the fastest method, but it's a short and neat one line of code:

$array = array_diff($array, array("string3"))

or if you're using PHP >5.4.0 or higher:

$array = array_diff($array, ["string3"])
Mikael Grön
  • 168
  • 2
  • 4
  • 4
    I bench-marked you method against GWW's in a for loop that runs 2.5 million times. Your's completed in 18 seconds (17 seconds when I didn't use variables), whereas GWW's completed in 16 seconds. So `array_diff` is slower as is deals with an array instead of a single string, causing overhead. If only there were a function like `array_diff` but for removing a single string in an array. – FluorescentGreen5 Mar 12 '17 at 07:19
  • 2
    @FluorescentGreen5 slower but no that much slower, that's only about 5-10% difference which is not worth losing sleep over unless you deal with hundreds of thousands of records, and it might be even less in PHP8 now – Tofandel Mar 15 '22 at 13:01
5

You can do this.

$arr = array("string1", "string2", "string3", "string4", "string5");
$new_arr=array();
foreach($arr as $value)
{
    if($value=="string3")
    {
        continue;
    }
    else
    {
        $new_arr[]=$value;
    }     
}
print_r($new_arr); 
ABorty
  • 2,512
  • 1
  • 13
  • 16
4

Use a combination of array_search and array_splice.

function array_remove(&$array, $item){
  $index = array_search($item, $array);
  if($index === false)
    return false;
  array_splice($array, $index, 1);
  return true;
}
Dustin Poissant
  • 3,201
  • 1
  • 20
  • 32
2

You can also try like this.

$array = ["string1", "string2", "string3", "string4", "string5"];
$key = array_search('string3',$array);
unset($array[$key]);
Sheetal Mehra
  • 478
  • 3
  • 13
1

It sort of depends how big the array is likely to be, and there's multiple options.

If it's typically quite small, array_diff is likely the fastest consistent solution, as Jorge posted.

Another solution for slightly larger sets:

$data = array_flip($data);
unset($data[$item2remove]);
$data = array_flip($data);

But that's only good if you don't have duplicate items. Depending on your workload it might be advantageous to guarantee uniqueness of items too.

Arantor
  • 597
  • 4
  • 15