Search in a PHP array using a specialized comparator

This is probably hopeless, but is there still a way to search for elements in an array with my own comparator function? Implementing this in PHP will lead to a slow search, so maybe a better solution exists?

What I really want from the search: a) find out if an element is present in the array and b) it is desirable to get the key (index) of the found element.

for instance

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

and if the comparator would look like this:

$comp = function ($arrValue, $findValue) {
    return ($arrValue % $findValue) == 0;
};

Then the search function based on the comparator will return trueif a search was found 8and, which would be nice, display the index of the found element, which is equal to 7.

+4
source share
2 answers

- :

$arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
$findValue = 8;

$result = array_filter(
    $arr, 
    function ($arrValue) use($findValue) {
        return ($arrValue % $findValue) == 0;
    }
);

, :

$arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
$findValue = 3;

foreach(array_filter(
    $arr, 
    function ($arrValue) use($findValue) {
        return ($arrValue % $findValue) == 0;
    }
) as $key => $value) {
    echo $value, ' is a multiple of ', $findValue, PHP_EOL;
}

№ 2

, :

function filter($values, $function) {
    return array_filter(
        $values,
        $function
    );
}

$isEven = function ($value) {
    return !($value & 1);
};

$isOdd = function ($value) {
    return $value & 1;
};

$data = range(1,10);

echo 'array_filter() for Odds', PHP_EOL;
var_dump(
    filter(
        $data,
        $isOdd
    )
);

echo 'array_filter() for Evens', PHP_EOL;
var_dump(
    filter(
        $data,
        $isEven
    )
);

PHP 5.5:

$isEven = function ($value) {
    return !($value & 1);
};

$isOdd = function ($value) {
    return $value & 1;
};

function xFilter(callable $callback, $args=array()) {
    foreach($args as $arg) {
        if (call_user_func($callback, $arg)) {
            yield $arg;
        }
    }
}

echo 'xFilter for Odds', PHP_EOL;
foreach(xFilter($isOdd, range(1,10)) as $i) {
    echo('num is: '.$i.PHP_EOL);
}

echo 'xFilter for Evens', PHP_EOL;
foreach(xFilter($isEven, range(1,10)) as $i) {
    echo('num is: '.$i.PHP_EOL);
}
+5

http://ideone.com/DSfppl

, array_search() - , . array_search - . , , a) b).

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

//finds if the value exist and returns key
$key = array_search(8, $array); 

//return key
echo $key;  //returns 7

:

- O (n).

0

Source: https://habr.com/ru/post/1543748/


All Articles