Tutorial :PHP: Remove all fcn not acting as expected, Code Inside Question:

I made this simple function (remove all \$elem from \$array):

``function remall(\$array, \$elem) {      for(\$i=0; \$i < count(\$array); \$i++)          if(\$array[\$i] == \$elem)              unset(\$array[\$i]);      \$newarray = array_values(\$array);      return \$newarray;  }  ``

But it isn't working perfectly, here are some inputs and outputs

``\$u = array(1, 7, 2, 7, 3, 7, 4, 7, 5, 7, 6, 7);  \$r = remall(\$u, 7);  Output of \$r: 12345767    \$n = array(7, 7, 1, 7, 3, 4, 6, 7, 2, 3, 1, -3, 10, 11, 7, 7, 7, 2, 7);  \$r = remall(\$n, 7);  Output of \$r: 1346231-30117727  ``

Notice how there are still 7s in my outputs. Also, My function will only be removing numbers from an array. Let me know if you spot something, thanks.

SOLUTION: Hey guys this is what worked for me (Thanks to Flavius Stef)

``function remall(\$array, \$elem) {      return array_values(array_diff(\$array, array(\$elem)));  }  ``

Solution:1

I'd go with

``return array_diff(\$array, array(\$elem));  ``

Solution:2

``function remall(\$array, \$elem) {      foreach(\$array as \$k => \$v)          if(\$v == \$elem)              unset(\$array[\$k]);      return \$array;  }  ``

Solution:3

Can you guarantee the input array is numeric (rather than associative) and without 'holes' in the keys?

You may want to use `foreach (\$array as \$key => \$value) { ... }` rather than `for (\$i=0; \$i < count(\$array); \$i++) { ... }`.

Aside from the caveat described in the first paragraph, the second approach (the one you're using now) evaluates `count()` each iteration of `for` - and `unset()` will change that value, naturally (first your array has ten elements, then after the first match, it'll have nine, and so forth).

Another option, sidestepping the need to make your own function entirely, would be for you to use `array_filter()` and supply a custom callback method, though that's not a very good option if your criterium changes a lot (which, it being a parameter in your example, it looks like it would be ;) ).

Edit: The best solution (most readable and most maintainable, while doing exactly what you want) would be to use `array_diff()`, as per Flavius Stef's answer:

``return array_diff(\$array, array(\$elem));  ``

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »