14

I have an array built from the URL of a webpage.

If an item in that array contains the ? symbol (The question mark symbol) then I want to remove that item from the array.

$array = ['news', 'artical', '?mailchimp=1'];

How could I do this? I've seen many examples where the searched string is the whole value, but not where it's just a single character or just part of the value.

4 Answers 4

22

http://www.php.net/manual/en/function.array-filter.php

function myFilter($string) {
  return strpos($string, '?') === false;
}

$newArray = array_filter($array, 'myFilter');
Sign up to request clarification or add additional context in comments.

Comments

12
foreach($array as $key => $one) {
    if(strpos($one, '?') !== false)
        unset($array[$key]);
}

Comments

8

If you're using >= PHP 5.3, use a closure.

$array = array_filter($array, function($value) {
   return strstr($value, '?') === false;
});

Comments

0

From PHP8, you can make calls of str_contain() inside array_filter() and invert its boolean return value.

Code: (Demo)

$array = ['news', 'artical', '?mailchimp=1'];

var_export(
    array_filter(
        $array,
        fn($v) => !str_contains($v, '?')
    )
);

The above will keep the original keys, so if you need to guarantee that your result array is indexed, just call array_values().

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.