Skip to content

Instantly share code, notes, and snippets.

@bartwttewaall
Last active April 29, 2021 08:01
Show Gist options
  • Save bartwttewaall/15d73c5b63a5b755b2adc24445ae5b3c to your computer and use it in GitHub Desktop.
Save bartwttewaall/15d73c5b63a5b755b2adc24445ae5b3c to your computer and use it in GitHub Desktop.
<?php
/**
* @return array
*/
public function getFilters()
{
return [
new TwigFilter('find', [$this, 'array_find']),
new TwigFilter('findIndex', [$this, 'array_find_index']),
];
}
/**
* @return mixed|null The found value
*
* @example:
* {% set items = [{id:1, name:"one"}, {id:2, name:"two"}, {id:3, name:"three"}] %}
* {{ items|find(i => i.name|length > 3)|json_encode }}
*/
public function array_find(array $array, callable $callback) {
foreach ($array as $key => $value) {
if (call_user_func($callback, $value, $key, $array) === true) return $value;
}
return null;
}
/**
* @return int The found index, or -1
*/
public function array_find_index(array $array, callable $callback) {
foreach ($array as $key => $value) {
if (call_user_func($callback, $value, $key, $array) === true) return $key;
}
return -1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment