0

For example:

main array is: array(0 => 'A', 1 => 'A', 2 => 'B', 3 => 'B', 4 => 'B');

pattern is: array('A', 'B');

expected answer: array( array(0, 2), array(1, 3) )

one more example:

main array array(0 => 'F', 5 => 'G', 78 => 'R', 2 => 'D');

pattern array('G', 'R', 'F');

expected answer: array(array(5, 78, 0))

How can I find all occurrences of pattern in array?

7
  • What does array(0, 2) and array(1, 3) mean? Commented Jul 10, 2012 at 16:02
  • @Rocket I think it is makes more sense to think of it as array( 'A' => array( 0, 2 ), 'B' => array( 1, 3 ) ) Commented Jul 10, 2012 at 16:03
  • @Rocket it's ids of pattern matched elements. In example there is two matched pairs -> (0,2) (1,3) Commented Jul 10, 2012 at 16:03
  • @Yekver: So for array(0, 2). The 0 is the index of A in the pattern array. and 2 is the number of As in the main array? Commented Jul 10, 2012 at 16:06
  • @Rocket: nope, for array(0, 2) the 0 is the index of A in the main array, and 2 is the index of B in the main array Commented Jul 10, 2012 at 16:10

2 Answers 2

2

Here's an function that uses recursion.

function array_pattern($array, $pattern){
    $ret = array(array());
    $found = true;
    foreach($pattern as $val){
        $x = array_search($val, $array);
        if($x === FALSE){
            $found = FALSE;
            break;
        }
        unset($array[$x]);
        $ret[0][] = $x;
    }
    return $found ? array_merge($ret, array_pattern($array, $pattern)) : array();
}

Call it like this:

$a = array_pattern(array(0 => 'A', 1 => 'A', 2 => 'B', 3 => 'B', 4 => 'B'), array('A', 'B'));
$b = array_pattern(array(0 => 'F', 5 => 'G', 78 => 'R', 2 => 'D'), array('G', 'R', 'F'));

DEMO: http://codepad.org/JCdsAMGk

Sign up to request clarification or add additional context in comments.

Comments

0

I didn't test the following code, but it may give you ideas.

$arr = array(0 => 'A', 1 => 'A', 2 => 'B', 3 => 'B', 4 => 'B');
$test = array('G', 'R', 'F');

$count = 0;
$count2 = 0; 
for($i=0;$i<count($arr);$++){
    $pass= true;
    if(count($test)+$count <= count($arr)){
        for($k=0;$k<count($test);$k++){
            if($arr[k+i]!=$test[k]){
                  $pass = false;
            }
        }
    }else{
       $pass = false;
    }

     if($pass){
       $output[$count2] = $i;
       $count2++;
     }


}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.