开发者

PHP Search Array Question

I need to have an array_search search my array strictly making sure that the item is identical (meaning the whole thing is the same thing as the input value). I know about the third variable in a array_search() function in PHP - the Strict one, but I don't want it to check if its the same instance, as it is not. How would I do this?

Here is the code I'm currently using:

array_search(some, array(someItem,anothervariable, yetanothervariable, some));开发者_开发百科 
//output - 0 (the first item) which contains some but isn't exactly some.

Requested output:

Instead of outputting the first item that contains some, someItem, it would output the key for the last item, 3, that is the exact search value.


Array search with strict is equivalent to the === operator.

Array search without strict is equivalent to the == operator.

If you need some sort of special comparison that isn't covered by either of them (comparing elements of objects for example) then you need to write a loop.


Are you open to using a foreach loop instead of array_search?

If so try this:

$haystack = array('something', 'someone', 'somewhere', 'some');
$needle = 'some';

foreach($haystack as $key=>$straw){
    if($straw === $needle){
        $straws[$key] = $straw;
        }
    }

print_r($straws);

it will print

Array ( [3] => some ) 

Or you could use array_keys() with the search value specified.

Then, using the same $haystack and $needle above:

$result = array_keys($haystack,$needle,TRUE);
print_r($result);

This returns:

Array ( [0] => 3 ) 

The first argument is the array to return keys from, The second arg is the search value, if you include this arg, then only keys from array elements that match the search value are returned. Including the third boolean arg tells the function to use match type as well (===).


Not really sure what you are asking but in PHP strict comparison is achieved with the triple equal sign (===). This means that both the value and the type must be the same. So if you compare a string "1" and an integer 1 with === it will fail. If strict is false then comparing string "1" with integer 1 would succeed. This is the meaning of strict in the array_search case. I implemented array_search below so you can see what it is doing.

function my_array_search($input, $search_array, $strict=false) {
        if(is_array($search_array)) {
            foreach($search_array as $key => $val) {
                if($strict === true) {
                    if($val === $input) {
                        return $key;
                    }
                } else {
                    if($val == $input) {
                        return $key;
                    }
                }

            }
        }

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜