I am building an AJAX powered smart search engine.

I work with keywords, so in the back-end script I explode the string provided by the AJAX.

( the string is the value of the search input field )

$keywords = $_POST["keywords"];
$keywords = strtolower($keywords);
$keyword = explode(" ", $keywords);

As You can see now, I have an array named $keyword containing all the keywords.

Now, I have to remove the values from the array whiches would result irrelevant results. To be more defined: I would like to remove all the rows with a value lenght less than 3.

I tried it in many ways, the last one was a simple foreach loop:

foreach ($keyword as $key => $value) {
if ( strlen($key[ $value ]) < 3 ) {
    unset($keyword[$key]);
   }
}

I read about array_filter, and functions like these, but - I mean - I can't imagine why it doesn't work this way.

Please if You have any ideas, write me an answer! Thanks for Your attention.

有帮助吗?

解决方案

You're nearly there with your loop, however $value is not a key within the $key variable. If you print_r your $keywords you will see that the $key variable will be the string on the left side of the => and the $value on the right.

Quick Fix:

if( strlen($value) < 3 )

Better fix:

$keywords = array_filter($keywords, function($x) { return strlen($x) >= 3; });

Nested fix

$keywords = array_filter(explode(' ',strtolower($_POST)), function($x) { return strlen($x) >= 3; });

Alternate fix (if you have a too old version of PHP that you cant do the anonymous functions above)

$keywords = array_filter(explode(' ',strtolower($_POST)), create_function('$x', 'return strlen($x) >= 3;'));

其他提示

The value of the array will be in $value not $key[$value].

Try

if ( strlen( $value ) < 3 ) {

You can use array_filter for that:

$keywords = array_filter($keywords, function($keyword) {
    return strlen($keyword) >= 3;
});

It will return an array with all keywords greater than 2 chars. Haven't tested it, but I think you get the idea.

Of course a plain foreach will do it to, but array_filter is less code and therefore easier to maintain and read. In terms of speed I guess there won't be any big differences.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top