5

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 .

1
  • $arr = array_filter($arr, function($value) { return strpos($value, 'Rs.') !== false; } Commented Nov 17, 2013 at 19:56

3 Answers 3

6

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

Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.