php callback as array value
preg_replace_callback_array
preg_replace_callback_array — Выполняет поиск и замену по регулярному выражению с использованием функций обратного вызова
Описание
Список параметров
Ассоциативный массив, связывающий шаблоны регулярного выражения (ключи) и callable (значения).
Строка, в которой будет производиться поиск и замена.
Если задан, то в указанную переменную будет записано количество произведённых замен.
Возвращаемые значения
preg_replace_callback_array() возвращает массив, если параметр subject является массивом и строку, если строкой. В случае возникновения ошибки возвращается null
Список изменений
Примеры
Пример #1 Пример использования preg_replace_callback_array()
Результат выполнения данного примера:
Смотрите также
User Contributed Notes 3 notes
Based on some tests, I found these important traits of the function. (These would
be nice to see documented as part of its spec, e.g. for confirmation. Without that,
this is just experimental curiosity. Still better than guesswork, though! 😉 )
1. Changes cascade over a subject across callbacks, i.e. a change made to a
subject by a callback will be seen by the next callback, if its pattern matches
the changed subject.
(But a change made by a previous call of the *same* callback (on any subject)
will not be seen by that callback again.)
3. The callback can’t be null (or ») for a quick shortcut for empty replacements.
This basically means that the «crown jewel», an even more efficient function:
«preg_replace_all_callback_array» is still missing from the collection.
5. (This last one is not specific to this function, but inherent to regexes, OTOH,
it’s probably more relevant here than anywhere else in PHP’s regex support.)
Even apparently simple cases can generate a crazy (and difficult-to-predict)
number of matches, and therefore callback invokations, so remember the set
$limit, where affordable. But, of course, try to sharpen your patterns first!
PHP array_filter, how to get the key in callback?
array_filter — Filters elements of an array using a callback function
Can callback get the key of the current array value and how?
6 Answers 6
From the documentation: PHP 5.6.0 Added optional flag parameter and constants ARRAY_FILTER_USE_KEY and ARRAY_FILTER_USE_BOTH
In a previous comment you outlined you’re actually looking for something like this:
There’s no way to let the callback of array_filter access the element’s key, nor is there a similar function that does what you want.
However, you can write your own function for this, like the one below:
By using the ARRAY_FILTER_USE_BOTH constant, you can get both value and key :
By using the ARRAY_FILTER_USE_KEY constant, you can get key alone :
You could use the array_walk function as discussed here (3rd answer down): is it possible if callback in array_filter receive parameter?
I didn’t like the other options suggested here, if anyone else is looking for this feature, here is a quick implementation:
The result of this function is exactly what it sounds like, it will return an array filtered by a callback function that receives the keys rather than the values.
EDIT: This is more of a disclaimer, after reading some of the other comments I realize that the OP is actually just looking for array_intersect as hakre pointed out. I will leave this answer here though since the OPs question does not clearly state that need and this page shows up in google for array_filter_keys
array_filter
(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)
array_filter — Фильтрует элементы массива с помощью callback-функции
Описание
Список параметров
Возвращаемые значения
Возвращает отфильтрованный массив.
Список изменений
Примеры
Пример #1 Пример использования array_filter()
Результат выполнения данного примера:
Результат выполнения данного примера:
Пример #3 array_filter() с указанным mode
Результат выполнения данного примера:
Примечания
Если callback-функция изменяет массив (например, добавляет или удаляет элементы), поведение этой функции неопределённо.
Смотрите также
User Contributed Notes 5 notes
If you like me have some trouble understanding example #1 due to the bitwise operator (&) used, here is an explanation.
The part in question is this callback function:
45 in binary: 101101
1 in binary: 000001
——
result: 000001
Some of PHP’s array functions play a prominent role in so called functional programming languages, where they show up under a slightly different name:
The array functions mentioned above allow you compose new functions on arrays.
This leads to a style of programming that looks much like algebra, e.g. the Bird/Meertens formalism.
E.g. a mathematician might state
map(f o g) = map(f) o map(g)
the so called «loop fusion» law.
Many functions on arrays can be created by the use of the foldr() function (which works like foldl, but eating up array elements from the right).
I can’t get into detail here, I just wanted to provide a hint about where this stuff also shows up and the theory behind it.
My favourite use of this function is converting a string to an array, trimming each line and removing empty lines:
Depending on the intended meanings of your «empty» array values, e.g., null and empty string, vs. an integer 0 or a boolean false, be mindful of the result of different filters.
declare( strict_types = 1 );
array (size=3)
‘intzero’ => int 0
‘stringzero’ => string ‘0’ (length=1)
‘stringfalse’ => string ‘false’ (length=5)
array (size=5)
‘nullstring’ => string » (length=0)
‘intzero’ => int 0
‘stringzero’ => string ‘0’ (length=1)
‘false’ => boolean false
‘stringfalse’ => string ‘false’ (length=5)
array (size=4)
‘intzero’ => int 0
‘stringzero’ => string ‘0’ (length=1)
‘false’ => boolean false
‘stringfalse’ => string ‘false’ (length=5)
Php callback as array value
Передача
Метод созданного объекта ( object ) передаётся как массив, содержащий объект по индексу 0 и имя метода по индексу 1. Доступ к закрытым и защищённым методам разрешён изнутри класса.
Помимо обычных пользовательских функций, в качестве callback-функции можно передавать анонимные функции и стрелочные функции.
Как правило, любой объект, реализующий __invoke(), также может быть передан в параметр callback.
Пример #1 Пример callback-функции
// Пример callback-функции
function my_callback_function () <
echo ‘Привет, мир!’ ;
>
// Пример callback-метода
class MyClass <
static function myCallbackMethod () <
echo ‘Привет, мир!’ ;
>
>
// Тип 1: Простой callback
call_user_func ( ‘my_callback_function’ );
// Тип 4: Вызов статического метода класса
call_user_func ( ‘MyClass::myCallbackMethod’ );
// Тип 5: Вызов относительного статического метода
class A <
public static function who () <
echo «A\n» ;
>
>
class B extends A <
public static function who () <
echo «B\n» ;
>
>
Пример #2 Пример callback-функции с использованием замыкания
Результат выполнения данного примера:
User Contributed Notes 17 notes
When specifying a call back in array notation (ie. array($this, «myfunc») ) the method can be private if called from inside the class, but if you call it from outside you’ll get a warning:
Warning: array_walk() expects parameter 2 to be a valid callback, cannot access private method mc::walkIt() in /in/tfh7f on line 22
— Using the name of a function as string has worked since at least 4.3.0
— Calling anonymous functions and invokable objects has worked since 5.3.0
— Using the array structure [$object, ‘method’] has worked since 5.4.0
Note, however, that the following are not supported when calling callbacks as variable functions, even though they are supported by call_user_func():
— Calling static class methods via strings such as ‘foo::doStuff’
— Calling parent method using the [$object, ‘parent::method’] array structure
All of these cases are correctly recognized as callbacks by the ‘callable’ type hint, however. Thus, the following code will produce an error «Fatal error: Call to undefined function foo::doStuff() in /tmp/code.php on line 4»:
static function doStuff () <
echo «Hello World!» ;
>
>
foo :: callIt ( ‘foo::doStuff’ );
?>
The code would work fine, if we replaced the ‘$callback()’ with ‘call_user_func($callback)’ or if we used the array [‘foo’, ‘doStuff’] as the callback instead.
You can use ‘self::methodName’ as a callable, but this is dangerous. Consider this example:
class Foo <
public static function doAwesomeThings () <
FunctionCaller :: callIt ( ‘self::someAwesomeMethod’ );
>
public static function someAwesomeMethod () <
// fantastic code goes here.
>
>
Foo :: doAwesomeThings ();
?>
This results in an error:
Warning: class ‘FunctionCaller’ does not have a method ‘someAwesomeMethod’.
For this reason you should always use the full class name:
:: callIt ( ‘Foo::someAwesomeMethod’ );
?>
I believe this is because there is no way for FunctionCaller to know that the string ‘self’ at one point referred to to `Foo`.
> As of PHP 5.2.3, it is also possible to pass ‘ClassName::methodName’
You can also use ‘self::methodName’. This works in PHP 5.2.12 for me.
If you pass a callable method to a function with a callable type declaration, the error message is misleading:
class X <
protected function foo (): void <>
>
I needed a function that would determine the type of callable being passed, and, eventually,
normalized it to some extent. Here’s what I came up with:
?>
Hope someone else finds it useful.
array_filter
(PHP 4 >= 4.0.6, PHP 5, PHP 7)
array_filter — Фильтрует элементы массива с помощью callback-функции
Описание
Список параметров
Возвращаемые значения
Возвращает отфильтрованный массив.
Список изменений
Версия | Описание |
---|---|
5.6.0 | Добавлен необязательный параметр flag и константы ARRAY_FILTER_USE_KEY и ARRAY_FILTER_USE_BOTH |
Примеры
Пример #1 Пример использования array_filter()
Результат выполнения данного примера:
Результат выполнения данного примера:
Пример #3 array_filter() с указанным flag
Результат выполнения данного примера:
Примечания
Если callback-функция изменяет массив (например, добавляет или удаляет элементы), поведение этой функции неопределено.
Смотрите также
User Contributed Notes 44 notes
In case you are interested (like me) in filtering out elements with certain key-names, array_filter won’t help you. Instead you can use the following:
Here is how you could easily delete a specific value from an array with array_filter:
array_filter remove also FALSE and 0. To remove only NULL’s use:
$af = [1, 0, 2, null, 3, 6, 7];
Some of PHP’s array functions play a prominent role in so called functional programming languages, where they show up under a slightly different name:
The array functions mentioned above allow you compose new functions on arrays.
This leads to a style of programming that looks much like algebra, e.g. the Bird/Meertens formalism.
E.g. a mathematician might state
map(f o g) = map(f) o map(g)
the so called «loop fusion» law.
Many functions on arrays can be created by the use of the foldr() function (which works like foldl, but eating up array elements from the right).
I can’t get into detail here, I just wanted to provide a hint about where this stuff also shows up and the theory behind it.
be careful with the above function «array_delete»‘s use of the stristr function, it could be slightly misleading. consider the following:
?>
Which filters all keys with «db» or «smarty» as their name (including objects which have a reference to those variables). The output of the above in a test case I did is the following:
Array
(
[userdata] => Array
(
[sid] => a130e675d380e0e9fe47897922d719ac
[not_in_db] =>
[user_id] => 1
[session_id] => 154
[permissions] => 1
[username] => tester
)
[systemobjects] => Array
(
[db] => **filtered by function**
[smarty] => **filtered by function**
)
)
Hi all,
Here’s a function that will look trough an array, and removes the array member when the search string is found.
if needle is left empty, the function will delete the array members that have no value (this means if it’s empty).
NOTE: It rebuilds the array from scratch, so keys begin with 0, like you would create a new array.
Example:
$array = array(«John», «Doe», «Macy»);
$array = array_clean($array, «doe», false);
print_r($array);
would return:
array
(
[0] => John
[1] => Macy
)
Hopes this helps someone 🙂
The following function modifies the supplied array recursively so that filtering is performed on multidimentional arrays as well, while preserving keys.
array_filter may not be used as it does not modify the array within itself.
Read «callback» parameter note with understanding (as well as «converting to boolean» chapter). Keep in midn, that 0, both:
* integer: 0 and
* float: 0.00
evaluates to boolean FALSE! And therefore all array nodes, that have such value WILL ALSO BE FILTERED by array_filter(), with default call back. Unless you provide your own callback function, that will (for example) filter only empty strings and NULLs, but leave «zeros» untouched.
Some people (including me) might be surprised to find this out.
I was looking for a function to delete values from an array and thought I had found it in array_filter(), however, I *didn’t* want the keys to be preserved *and* I needed blank values cleaned out of the array as well. I came up with the following (with help from many of the above examples):