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
- How does binary search work with arrays and lists?ComputerScienceOne · Sorting
- How can strings be used as indices in PHP arrays?ComputerScienceOne · Non-Contiguous Indices
- Can PHP array indices be non-contiguous?ComputerScienceOne · Strings as Indices
- How can you iterate over indexed and associative arrays in PHP?ComputerScienceOne · Iteration
- How do you create and index arrays in PHP?ComputerScienceOne · Creating Arrays
- How can key-value pairs be initialized in a PHP array?ComputerScienceOne · Non-Contiguous Indices
- How can you extract array keys and values and compare arrays in PHP?ComputerScienceOne · Iteration