user10753862
user10753862

Reputation:

unset array item if it has certain word in it Php

Trying to unset an array items. which include "list" word in it. I tried some ways, but didn't managed it. I must doing something wrong in my code I guess...

Array is:

[0]=>
  string(41) "http://www.sumitomo-rd-mansion.jp/kansai/"
  [1]=>
  string(43) "http://www.sumitomo-rd-mansion.jp/hokkaido/"
  [2]=>
  string(41) "http://www.sumitomo-rd-mansion.jp/tohoku/"
  [3]=>
  string(62) "http://www.sumitomo-rd-mansion.jp/sp/list.html?area=areaKansai"
  [4]=>
  string(64) "http://www.sumitomo-rd-mansion.jp/sp/list.html?area=areaHokkaido"
  [5]=>
  string(62) "http://www.sumitomo-rd-mansion.jp/sp/list.html?area=areaTohoku"

Try to delete items which include "list" word and so I tried this.

    $needle = "list";

    if (($index = array_search($needle, $allArea)) !== false) {
        unset($allArea[$index]);
    } 

But still it returns all items... How can I fix the code?

Upvotes: 2

Views: 59

Answers (1)

Phil
Phil

Reputation: 164766

The issue here is that array_search() is comparing each string entry with $needle like

$url == $needle

This means you'll never get a match unless the entry is literally "needle". Even if it does match, it only returns the first entry found.

You may find a filter operation more successful

$needle = 'list';
$filteredAreas = array_filter($allArea, function($url) use($needle) {
    return strpos($url, $needle) === false; // filters out URLs containing $needle
});

Upvotes: 5

Related Questions