php array filter null

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

Is there any function to do what I want?

php array filter null. Смотреть фото php array filter null. Смотреть картинку php array filter null. Картинка про php array filter null. Фото php array filter null

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

php array filter null. Смотреть фото php array filter null. Смотреть картинку php array filter null. Картинка про php array filter null. Фото php array filter null

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.

php array filter null. Смотреть фото php array filter null. Смотреть картинку php array filter null. Картинка про php array filter null. Фото php array filter null

One-liners are always nice.

Explanation:

EDIT:

Источник

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)

Источник

Поделиться

doctor Brain

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

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

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

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

php array filter null. Смотреть фото php array filter null. Смотреть картинку php array filter null. Картинка про php array filter null. Фото php array filter null

К счастью, функция 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.

Источник

PHP: How to use array_filter() to filter array keys?

The callback function in array_filter() only passes in the array’s values, not the keys.

15 Answers 15

Since PHP 7.4 introduced arrow functions we can make this more succinct:

I needed to do same, but with a more complex array_filter on the keys.

Here’s how I did it, using a similar method.

This outputs the result:

Here is a more flexible solution using a closure:

So in the function, you can do other specific tests.

php array filter null. Смотреть фото php array filter null. Смотреть картинку php array filter null. Картинка про php array filter null. Фото php array filter null

If you are looking for a method to filter an array by a string occurring in keys, you can use:

The result of print_r($mResult) is

An adaption of this answer that supports regular expressions

php array filter null. Смотреть фото php array filter null. Смотреть картинку php array filter null. Картинка про php array filter null. Фото php array filter null

How to get the current key of an array when using array_filter

It passes the array you’re filtering as a reference to the callback. As array_filter doesn’t conventionally iterate over the array by increasing it’s public internal pointer you have to advance it by yourself.

What’s important here is that you need to make sure your array is reset, otherwise you might start right in the middle of it.

In PHP >= 5.4 you could make the callback even shorter:

Starting from PHP 5.6, you can use the ARRAY_FILTER_USE_KEY flag in array_filter :

Otherwise, you can use this function (from TestDummy):

And here is an augmented version of mine, which accepts a callback or directly the keys:

Last but not least, you may also use a simple foreach :

Here’s a less flexible alternative using unset():

The result of print_r($array) being:

This is not applicable if you want to keep the filtered values for later use but tidier, if you’re certain that you don’t.

php array filter null. Смотреть фото php array filter null. Смотреть картинку php array filter null. Картинка про php array filter null. Фото php array filter null

array filter function from php:

For Example : Consider simple array

If you want to filter array based on the array key, We need to use ARRAY_FILTER_USE_KEY as third parameter of array function array_filter.

If you want to filter array based on the array key and array value, We need to use ARRAY_FILTER_USE_BOTH as third parameter of array function 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):

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *