Remove string from PHP array?

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"])

$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.


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;
}

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); 

Tags:

Php

Arrays

String