Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP delete value from array if var is found in the value

Tags:

arrays

php

I have an array that looks like this:

Array
(
   [0] => aaaaa
   [1] => bbbbb
   [2] => ccxcc
   [3] => ddddd
)

I want do delete every value of the array that contains the letter x, so this would be the outcome:

Array
(
   [0] => aaaaa
   [1] => bbbbb
   [2] => ddddd
)

How would I do this?

Thanks!

like image 332
BBR Avatar asked Jun 11 '26 05:06

BBR


2 Answers

You can use array_filter()

$output = array_filter($input, function ($v) { return strpos($v, 'x') === FALSE; });

If you are using PHP < 5.3.0:

function filter_x($v) { 
    return strpos($v, 'x') === FALSE; 
}

$output = array_filter($input, 'filter_x');
like image 179
NullUserException Avatar answered Jun 13 '26 19:06

NullUserException


foreach ($array as $k => $v) { // Loop the array
  if (strpos($v,'x') !== FALSE) { // Check if $v has a letter x in it
    unset($array[$k]); // Delete the element
  }
}
array_merge($array); // Put the remaining keys in a contiguous order
like image 25
DaveRandom Avatar answered Jun 13 '26 19:06

DaveRandom



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!