Created
June 10, 2011 02:46
-
-
Save hakre/1018156 to your computer and use it in GitHub Desktop.
search array in array note
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$for = array('ac', 'bc'); | |
$in = array('ax', 'ac', 'bc', 'cc'); | |
echo search($for, $in); // 1 | |
/** | |
* Search non-keyed array $for in non-keyed array $in | |
* and returning it's index position, or false if not | |
* found. | |
* | |
* both arrays contain unique values only. | |
* | |
* @return false|int | |
*/ | |
function search(array $for, array $in) { | |
list($for, $in) = array_map('array_values', array($for, $in)); | |
$result = false; | |
# can not look up nothing in empty or too small array | |
(count($for)&&max(0,1+count($in)-($len=count($for)))) | |
# flip for quick lookup (otherwise use array_search()) | |
&& ($flip=array_flip($in)) | |
# there can only be one match | |
&& isset($flip[$for[0]]) | |
# and that's the start | |
&& (($pos=$flip[$for[0]])?1:1) | |
# to check everything to match | |
&& (array_slice($in, $pos, $len)===$for) | |
# found! | |
&& $result=$pos | |
; | |
return $result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment