Concept
How does PHP search arrays?
"PHP provides a linear search function, array_search() that can be used to search for an element in an array. The array can be specified to use loose comparisons (default) or strict comparisons. It returns the key (i.e. index) of the first matching element it finds and false if the search was unsuccessful. For example:\n\n$arr = array(10, 8, 3, 12, 4, 42, 7, 108);\n\n$index = array_search(12, $arr); //index is now 3\n\n$arr = array(\"hello\", 10, \"mixed\", 12, \"20\");\n\n//a loose search:\n\n$index = array_search(20, $arr); //index is now 4\n\n//a strict search:\n\n$index = array_search(20, $arr, false); //index is now false.\n\nPHP does not provide a standard binary search function. Though you can write your own binary search implementation, likely the reason that that PHP does not provide one is because one is not needed. The purpose of binary search is to search a sorted array efficiently. However, PHP arrays are not usual arrays: they are associative arrays, essentially key-value maps. Retrieving an element via its key is essentially a constant-time operation, even more efficient that binary search. A better solution may be to simply store the elements using a proper key which can be used to retrieve the element later on."
Related Ideas
- How can PHP arrays be sorted?ComputerScienceOne · Searching
- What is a comparator function and how does it determine element order?ComputerScienceOne · Comparator Functions
- How can comparator functions order Student structures?ComputerScienceOne · Comparator Functions
- How does a Comparator determine the order of two elements?ComputerScienceOne · Comparators
- How do you implement a comparator for integers in C?ComputerScienceOne · Comparator Functions