[ create a new paste ] login | about

Link: http://codepad.org/0LVEkIwV    [ raw code | output | fork ]

PHP, pasted on Jun 10:
<?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;
}


Output:
1
1


Create a new paste based on this one


Comments: