Anisha Virat
Anisha Virat

Reputation: 259

Remove element from array if string contains any of the characters

Remove element from array if string contains any of the characters.For example Below is the actual array.

array(1390) {
  [0]=>
  string(9) "Rs.52.68""
  [1]=>
  string(20) ""php code generator""
  [2]=>
  string(9) ""Rs.1.29""
  [3]=>
  string(21) ""php codes for login""
  [4]=>
  string(10) ""Rs.70.23""

 } 

I need the array to remove all the elements which start with RS.

Expected Result

 array(1390) {
      [0]=>
      string(20) ""php code generator""
      [1]=>
      string(21) ""php codes for login""


     } 

What i tried so far :

foreach($arr as $ll)
{

if (strpos($ll,'RS.') !== false) {
    echo 'unwanted element';
}

From above code how can i remove unwanted elements from array .

Upvotes: 5

Views: 6162

Answers (3)

Tom Tom
Tom Tom

Reputation: 3698

Rs is different than RS you want to use stripos rather than strpos for non case sensitive checking

foreach($arr as $key => $ll)
{    
  if (stripos($ll,'RS.') !== false) {
    unset($arr[$key]);
  }
}

or use arrayfilter as pointed out

Upvotes: 0

GolezTrol
GolezTrol

Reputation: 116110

This sounds like a job for array_filter. It allows you to specify a callback function that can do any test you like. If the callback returns true, the value if returned in the resulting array. If it returns false, then the value is filtered out.

$arr = array_filter($arr, 
  function($item) { 
    return strpos($item, 'Rs.') === false; 
  });

Upvotes: 3

h2ooooooo
h2ooooooo

Reputation: 39532

You can get the $key in the foreach loop and use unset() on your array:

foreach ($arr as $key => $ll) {
    if (strpos($ll,'RS.') !== false) {
        unset($arr[$key]);
    }
}

Note that this would remove none of your items as "RS" never appears. Only "Rs".

Upvotes: 6

Related Questions