PHP » PYTHON |
login |
register |
about
|
PYTHON array_search
is this article helpful?
|
Python replacement for PHP's array_search
[
edit
| history
]
# It works just for lists, that are number-indexed arrays: haystack.index(needle) # It works for dictionaries, that allows text-indexed values index = [k for k, v in haystack.iteritems() if v == needle][0] or a new not-sure optimally but works for both list and dict def array_search(needle, haystack, strict=False): if not strict: needle = str(needle) if is_array(haystack): if is_array_assoc(haystack): if not strict: key = [k for k, v in haystack.items() if str(v) == needle] count_ = count(key) return key[0] if count_ > 0 else False else: key = [k for k, v in haystack.items() if v == needle] count_ = count(key) return key[0] if count_ > 0 else False else: key = 0 if not strict: for item in haystack: if str(item) == needle: return key key += 1 else: for item in haystack: if item == needle: return key key += 1 return False else: return False array_search(PHP 4 >= 4.0.5, PHP 5) array_search — Searches the array for a given value and returns the corresponding key if successful DescriptionSearches haystack for needle . Parameters
Return ValuesReturns the key for needle if it is found in the array, FALSE otherwise. If needle is found in haystack more than once, the first matching key is returned. To return the keys for all matching values, use array_keys() with the optional search_value parameter instead. Warning
This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE, such as 0 or "". Please read the section on Booleans for more information. Use the === operator for testing the return value of this function. Changelog
Examples
Example #1 array_search() example
<?php
See Also
|
more
Recently updated
more
Most requested
more
Last requests
|