1

From the code below I can compare the 2 arrays and find out the $subset elements position range in $array.

$array = [8,2,3,7,4,6,5,1,9];
$subset = [6,3,7];

function get_range($array, $subset)
{
    $min = sizeof($array);
    $max = 0;
    
    foreach($subset as $value) {
        $occurrence = array_search($value, $array);
        if( $occurrence < $min ) {
            $min = $occurrence;
        }
        if( $occurrence >  $max ) {
            $max = $occurrence;
        }
    }
    
    return [$min, $max];
}
$range = get_range($array, $subset);  // result as an array -> [2, 5]

However, I want to do a recursive array_search for my multidimentional array like:

$subset =  array (
  array(6,3,7),
  array(4,2,9),
  array(3,5,6),
);

How can I do this? Expecting results -> [2, 5], [1, 8], [2, 6].

3
  • Why do you need a recursion? Commented Jan 17, 2022 at 8:08
  • Does this help you answer the question? stackoverflow.com/questions/7694843/… Commented Jan 17, 2022 at 8:08
  • @ Zhorov my $subset array to compare with is dynamic and generated from scripts, I'm thinking to save the array_search results into an array but don't know how. @PatricNox I've seen the thread but no help, I need the smaller array $subset elements position range as shown above. Commented Jan 17, 2022 at 8:20

1 Answer 1

1

You do not need a recursion here, simply add an additional loop in the get_range() function. The following example is based on your code and is a possible solution to your problem:

<?php
$array = [8,2,3,7,4,6,5,1,9];
$subsets =  array (
  array(6,3,7),
  array(4,2,9),
  array(3,5,6),
);

function get_range($array, $subsets)
{
    $result = array();
    foreach ($subsets as $subset) {
        $min = sizeof($array);
        $max = 0;
        foreach($subset as $value) {
            $occurrence = array_search($value, $array);
            if( $occurrence < $min ) {
                $min = $occurrence;
            }
            if( $occurrence >  $max ) {
                $max = $occurrence;
            }
        }
        $result[] = [$min, $max];
    }
    
    return $result;
}

$range = get_range($array, $subsets);
echo print_r($range, true);
?>

Result:

Array ( 
    [0] => Array ( [0] => 2 [1] => 5 ) 
    [1] => Array ( [0] => 1 [1] => 8 ) 
    [2] => Array ( [0] => 2 [1] => 6 ) 
)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, this works! and is exactly what I want.

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.