Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove element from array if string contains any of the characters

Tags:

arrays

php

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 .

like image 724
Anisha Virat Avatar asked Nov 17 '13 19:11

Anisha Virat


2 Answers

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

like image 192
h2ooooooo Avatar answered Sep 28 '22 04:09

h2ooooooo


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; 
  });
like image 23
GolezTrol Avatar answered Sep 28 '22 04:09

GolezTrol