2

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!

3 Answers 3

9

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');
Sign up to request clarification or add additional context in comments.

3 Comments

Yes! Got to love array_filter
Thanks, I use PHP < 5.3.0 though
One could use use to make the filter callback function a bit more flexible. Like: function ($val) use ($char) { return strpos($val, $char) === false; }.
1
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

Comments

1
for($i = 0; $i < count($array); $i++) {
    if(strpos($array[$i], 'x') !== false) {
        unset($array[$i]);
    }
}

2 Comments

DaveRandom's idea was better as it arranged the array with array_merge but still thanks!
Yeah, totally missed that you wanted the array reindexed :P

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.