array filter strlen php

PHP array_filter Function

Summary: in this tutorial, you’ll learn how to use the PHP array_filter() function to filter elements of an array using a callback function.

Introduction to PHP array_filter() function

When you want to filter elements of an array, you often iterate over the elements and check whether the result array should include each element.

The array_filter() function makes the code less verbose and more expressive:

From PHP 7.4, you can can use the arrow function instead of the anonymous function like this:

The array_filter() function allows you to filter elements of an array using a callback function.

The following ilustrates the syntax of the array_filter() function:

PHP array_filter() function examples

Let’s take some examples to understand the array_filter() function better.

1) Basic array_filter() function example

2) Using callback as a method of a class

Besides a callback, you can pass a method of a class to the array_filter() function like this:

To use the isOdd() method as the callback of the array_filter() function, you use the following form:

If you have a class that has is a static method, you pass the static method as the callback of the array_filter() function:

The following uses the isEven() static method as the callback of the array_fitler() function:

From PHP 5.3, if a class implements the __invoke() magic method, you can use it as a callable. For example:

In this example, the Positive class has the __invoke() magic method that returns true if the argument is positive; otherwise, it returns false.

You can pass an instance of the Positive class to the array_filter() function for including only positive numbers in the result array.

Passing elements to the callback function

By default, the array_filter() function passes the value of each array element to the callback function for filtering.

Sometimes, you want to pass the key, not value, to the callback function. In this case, you can pass ARRAY_FILTER_USE_KEY as the third argument of the array_filter() function. For example:

To pass both the key and value of the element to the callback function, you pass the ARRAY_FILTER_USE_BOTH value as the third argument of the array_filter() function. For example:

In this tutorial, you have learned how to use the PHP array_filter() function to filter elements of an array using a callback.

Источник

Поделиться

doctor Brain

мир глазами веб-разработчика

PHP: фильтрация массивов

фильтруем многомерный массив по ключу и значению

время чтения 5 мин.

К счастью, функция array_filter не ограничена только возможностью удалять из массива значения, соответствующие логическому false. В качестве второго параметра array_filter может использовать весьма полезные callback-функции, а это означает, что мы можем делать с массивом, практически все, что захотим.

Давайте рассмотрим возможность фильтрации многомерного массива по ключу и значению.

Исходный массив

Для начала, нам нужны какие-то данные, например, этот небольшой многомерный массив:

Читайте также:  Клонит в сон коронавирус

Конечно, для лучшего представления данных пригодится функция var_dump:

Фильтрация многомерного массива по ключу

Теперь попробуем отфильтровать массив по ключу (key). Напомню, что в нашем массиве есть два главных ключа: ‘PHPDevelopers’ и ‘C#Developers’. Давайте предположим, что нам требуются только данные для ‘PHPDevelopers’.

По умолчанию функция array_filter возвращает только значения. С помощью третьего параметра мы можем явно указать, что нам требуются только ключи (ARRAY_FILTER_USE_KEY) или и ключи и значения (ARRAY_FILTER_USE_BOTH).

Вот так будет выглядеть наша функция:

Давайте посмотрим, что произойдет, если мы забудем указать третий параметр для array_filter:

Фильтрация многомерного массива по значению

А теперь попробуем отфильтровать в массиве php-разработчиков (PHP Developers) старше сорока лет.

Обратите внимание на следующие моменты:

Получится следующая функция:

Итак, мы отобрали три записи, в каждой из которых возраст разработчика превышает 40 лет:

Вывод

Функция array_filter дает практически неограниченные возможности, например: для простого отбора данных в большом массиве или для фильтрации свойств выбранных в интернет-магазине товаров.

Не забывайте изучить полную документацию для array_filter.

Источник

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):

Источник

I used array_filter but it removes the 0 ‘ s also.

Is there any function to do what I want?

9 Answers 9

Or if you don’t want to define a filtering function, you can also use an anonymous function (closure):

If you just need the numeric values you can use is_numeric as your callback: example

If you want to remove NULL, FALSE and Empty Strings, but leave values of 0, you can use strlen as the callback function:

When converting to boolean, the following values are considered FALSE:

Every other value is considered TRUE (including any resource).

You can pass a second parameter to array_filter with a callback to a function you write yourself, which tells array_filter whether or not to remove the item.

Assuming you want to remove all FALSE-equivalent values except zeroes, this is an easy function to write:

Then you just overwrite the original array with the filtered array:

Use a custom callback function with array_filter. See this example, lifted from PHP manual, on how to use call back functions. The callback function in the example is filtering based on odd/even; you can write a little function to filter based on your requirements.

One-liners are always nice.

Explanation:

EDIT:

Источник

PHP: как использовать array filter() для фильтрации ключей массива?

функция обратного вызова в array_filter() передает только значения массива, а не ключи.

13 ответов:

мне нужно сделать то же самое, но с более сложным array_filter на клавишах.

вот как я это сделал, используя аналогичный метод.

вот это более гибкое решение с помощью закрытия:

Так что в функции, вы можете сделать другие конкретные тесты.

если вы ищете метод для фильтрации массива по строке, встречающейся в ключах, вы можете использовать:

результат print_r($mResult) и

адаптация этого ответа, который поддерживает регулярные выражения

как получить текущий ключ массива при использовании array_filter

он передает массив, который вы фильтруете, как ссылку на обратный вызов. Как array_filter обычно не перебирает массив, увеличивая его публичный внутренний указатель вы должны продвигать его самостоятельно.

здесь важно то, что вам нужно убедиться, что Ваш массив сброшен, иначе вы можете начать прямо в середине его.

на PHP > = 5.4 вы можете сделать обратный вызов еще короче:

вот менее гибкая альтернатива с помощью unset ():

результат print_r($array) время:

Это не применимо, если вы хотите сохранить отфильтрованы значения для последующего использования, но аккуратнее, если вы уверены, что это не так.

начиная с PHP 5.6, вы можете использовать ARRAY_FILTER_USE_KEY флаг array_filter :

В противном случае, вы можете использовать эту функцию (от TestDummy):

А вот дополненная версия моей, которая принимает обратный вызов или непосредственно ключи:

И последнее, но не менее важное, вы также можете использовать простой foreach :

возможно, перебор, если вам это нужно только один раз, но вы можете использовать YaLinqo библиотека* для фильтрации коллекций (и выполнения любых других преобразований). Эта библиотека позволяет формировать SQL-подобные запросы на объекты с плавным синтаксисом. Его where функция принимает обратный вызов с двумя аргументами: значение и ключ. Например:

С помощью этой функции можно фильтровать многомерный массив

функция фильтра массива из php:

$array-это входной массив

Например : рассмотрим простой массив

если вы хотите фильтровать массив на основе ключ массива, нам нужно использовать ARRAY_FILTER_USE_KEY как третий параметр функции массива array_filter.

если вы хотите фильтровать массив на основе ключ массива и значение массива, нам нужно использовать ARRAY_FILTER_USE_BOTH как третий параметр функции array array_filter.

пример функции обратного вызова:

/ / отфильтровать элементы массива с ключами короче 4 символов // С помощью анонимной функции с закрытием.

$output = array_filter(array_keys ($input), сравнение(4));

функция для удаления некоторых элементов массива

Источник

Читайте также:  обучение на кондитера вуз
Образовательный портал