Skip to content

Instantly share code, notes, and snippets.

@hakre
Created June 10, 2011 02:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save hakre/1018156 to your computer and use it in GitHub Desktop.
Save hakre/1018156 to your computer and use it in GitHub Desktop.
search array in array note
<?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