php array remove empty values

php remove «empty» values in array

I’m trying to clean an array from empty values by using the following function:

The empty values don’t go away, I fail to identify them..

. might be some encoding problem or something.. it doesnt look like multibyte characters.. the result i get is:

php array remove empty values. Смотреть фото php array remove empty values. Смотреть картинку php array remove empty values. Картинка про php array remove empty values. Фото php array remove empty values

php array remove empty values. Смотреть фото php array remove empty values. Смотреть картинку php array remove empty values. Картинка про php array remove empty values. Фото php array remove empty values

4 Answers 4

You can use the PHP function array_filter() to remove the empty values

This will print out:

php array remove empty values. Смотреть фото php array remove empty values. Смотреть картинку php array remove empty values. Картинка про php array remove empty values. Фото php array remove empty values

You can use the PHP function array_filter() to remove the empty values with callback function as below

This will print out:

php array remove empty values. Смотреть фото php array remove empty values. Смотреть картинку php array remove empty values. Картинка про php array remove empty values. Фото php array remove empty values

Not very sure what you did in that code of yours but here is something that can remove empty elements from a php array

Code Snippet

php array remove empty values. Смотреть фото php array remove empty values. Смотреть картинку php array remove empty values. Картинка про php array remove empty values. Фото php array remove empty values

Removing empty array slots in PHP, leaving holes in the array.

A quick way to remove empty elements from an array is using array_filter without a callback function. This will also remove 0s (zeroes) though.

Alternatively, array_diff allows you to decide which elements to keep. The following example will only remove empty strings, but keep 0

Removing empty array slots in PHP, and compacting the array.

Both functions leave ‘gaps’ where the empty entries used to be. You can see it below, where the indices are [1] and [3] and not [0] and [1].

array_slice can remove those gaps:

so now for your cas, Example

inital output:

Array ( [0] => [1] => BEGIN:VCARD [2] => [3] => [4] => [5] => [6] => [7] => VERSION:2.1 )

final ouput :

Array ( [0] => BEGIN:VCARD [1] => VERSION:2.1 )

Источник

How to remove empty values from multidimensional array in PHP?

I’ve been looking a lot of answers, but none of them are working for me.

I’m looking for a way to remove the subarrays with empty values like [12] [1] and [2] while keeping everything else.

The desired result:

I tried a lot of the functions on the official php docs and none of them worked.

But it only removes the element in the subarrays; I need the subarrays to be removed entirely.

php array remove empty values. Смотреть фото php array remove empty values. Смотреть картинку php array remove empty values. Картинка про php array remove empty values. Фото php array remove empty values

8 Answers 8

Bit late, but may help someone looking for same answer. I used this very simple approach to;

php array remove empty values. Смотреть фото php array remove empty values. Смотреть картинку php array remove empty values. Картинка про php array remove empty values. Фото php array remove empty values

The following function worked for my case. We can use a simple recursive function to remove all empty elements from the multidimensional PHP array:

Then we just need to call this function:

php array remove empty values. Смотреть фото php array remove empty values. Смотреть картинку php array remove empty values. Картинка про php array remove empty values. Фото php array remove empty values

Not sure if this is exactly what your looking for.

I’m sure better checking and making this more robust might help the solution.

php array remove empty values. Смотреть фото php array remove empty values. Смотреть картинку php array remove empty values. Картинка про php array remove empty values. Фото php array remove empty values

php array remove empty values. Смотреть фото php array remove empty values. Смотреть картинку php array remove empty values. Картинка про php array remove empty values. Фото php array remove empty values

php array remove empty values. Смотреть фото php array remove empty values. Смотреть картинку php array remove empty values. Картинка про php array remove empty values. Фото php array remove empty values

Use array_filter with array_map like below:

php array remove empty values. Смотреть фото php array remove empty values. Смотреть картинку php array remove empty values. Картинка про php array remove empty values. Фото php array remove empty values

php array remove empty values. Смотреть фото php array remove empty values. Смотреть картинку php array remove empty values. Картинка про php array remove empty values. Фото php array remove empty values

Because the subarrays in your array only have one element each, you can simplify the approach using either of the two following methods. The logical advantage is in avoiding the functional iterator ( array_filter ) on the second level elements. This is why current() is more suitable for this question/page.

Both output the same result (which purposely removes empty values and preserves 0 values)

If the OP’s 2nd level array held more than one element AND the OP wanted to remove all zero-ish, false-y, empty, null elements (meaning zeros are not wanted or guaranteed not to occur), then Alastair F’s answer would be the best choice.

If the OP’s input array had an unknown number of levels AND zero-ish/false-y/empty/null elements should be removed, then Reza Mamun’s answer is a logical, recursive approach.

My point being (and my motivation behind spending so much time and care to answer this question) that array_filter() is greedy and if you aren’t aware of this default behavior, your project may silently output incorrect information. I hope this explanation saves programmers some time and strife.

Источник

Recursively remove empty elements and subarrays from a multi-dimensional array

I can’t seem to find a simple, straight-forward solution to the age-old problem of removing empty elements from arrays in PHP.

My input array may look like this:

(And so on, if there’s more data, although there may not be. )

If it looks like the above, I want it to be completely empty after I’ve processed it.

So print_r($array); would output:

Warning: array_filter() [function.array-filter]: The second argument, ’empty_array’, should be a valid callback

What am I doing wrong?

php array remove empty values. Смотреть фото php array remove empty values. Смотреть картинку php array remove empty values. Картинка про php array remove empty values. Фото php array remove empty values

php array remove empty values. Смотреть фото php array remove empty values. Смотреть картинку php array remove empty values. Картинка про php array remove empty values. Фото php array remove empty values

6 Answers 6

php array remove empty values. Смотреть фото php array remove empty values. Смотреть картинку php array remove empty values. Картинка про php array remove empty values. Фото php array remove empty values

There are numerous examples of how to do this. You can try the docs, for one (see the first comment).

Granted this example doesn’t actually use array_filter but you get the point.

The accepted answer does not do exactly what the OP asked. If you want to recursively remove ALL values that evaluate to false including empty arrays then use the following function:

Or you could change the return condition according to your needs, for example:

If you only want to remove empty arrays. Or you can change the condition to only test for «» or false or null, etc.

Following up jeremyharris’ suggestion, this is how I needed to change it to make it work:

php array remove empty values. Смотреть фото php array remove empty values. Смотреть картинку php array remove empty values. Картинка про php array remove empty values. Фото php array remove empty values

php array remove empty values. Смотреть фото php array remove empty values. Смотреть картинку php array remove empty values. Картинка про php array remove empty values. Фото php array remove empty values

array_filter() is not type-sensitive by default. This means that any zero-ish, false-y, null, empty values will be removed. My links to follow will demonstrate this point.

The OP’s sample input array is 2-dimensional. If the data structure is static then recursion is not necessary. For anyone who would like to filter the zero-length values from a multi-dimensional array, I’ll provide a static 2-dim method and a recursive method.

Static 2-dim Array: This code performs a «zero-safe» filter on the 2nd level elements and then removes empty subarrays: (See this demo to see this method work with different (trickier) array data)

Here is the same code as a one-liner:

Output (as originally specified by the OP):

*if you don’t want to remove the empty subarrays, simply remove the outer array_filter() call.

Recursive method for multi-dimensional arrays of unknown depth: When the number of levels in an array are unknown, recursion is a logical technique. The following code will process each subarray, removing zero-length values and any empty subarrays as it goes. Here is a demo of this code with a few sample inputs.

If anyone discovers an input array that breaks my recursive method, please post it (in its simplest form) as a comment and I’ll update my answer.

Источник

Remove empty array elements

Some elements in my array are empty strings based on what the user has submitted. I need to remove those elements. I have this:

php array remove empty values. Смотреть фото php array remove empty values. Смотреть картинку php array remove empty values. Картинка про php array remove empty values. Фото php array remove empty values

27 Answers 27

You can use array_filter to remove empty elements:

If you have (int) 0 in your array, you may use the following:

EDIT: Maybe your elements are not empty per se but contain one or more spaces. You can use the following before using array_filter

The most popular answer on this topic is absolutely INCORRECT.

Consider the following PHP script:

Why is this? Because a string containing a single ‘0’ character also evaluates to boolean false, so even though it’s not an empty string, it will still get filtered. That would be a bug.

Passing the built-in strlen function as the filtering function will work, because it returns a non-zero integer for a non-empty string, and a zero integer for an empty string. Non-zero integers always evaluate to true when converted to boolean, while zero integers always evaluate to false when converted to boolean.

So, the absolute, definitive, correct answer is:

array_filter: «If no callback is supplied, all entries of input equal to FALSE will be removed.» This means that elements with values NULL, 0, ‘0’, », FALSE, array() will be removed too.

The other option is doing

which will remove elements with values NULL, » and FALSE.

UPDATE

Here is an example.

php array remove empty values. Смотреть фото php array remove empty values. Смотреть картинку php array remove empty values. Картинка про php array remove empty values. Фото php array remove empty values

php array remove empty values. Смотреть фото php array remove empty values. Смотреть картинку php array remove empty values. Картинка про php array remove empty values. Фото php array remove empty values

Another one liner to remove empty («» empty string) elements from your array.

Or maybe you want to trim your array elements first:

Note: This code also removes null and false elements.

php array remove empty values. Смотреть фото php array remove empty values. Смотреть картинку php array remove empty values. Картинка про php array remove empty values. Фото php array remove empty values

In short:

This is my suggested code:

Explanation:

array_map is for trimming, array_filter is for remove empty values, strlen is for keep 0 value, and array_values is for re indexing if you needed.

Samples:

Results:

Online Test:

If you are working with a numerical array and need to re-index the array after removing empty elements, use the array_values function:

The most voted answer is wrong or at least not completely true as the OP is talking about blank strings only. Here’s a thorough explanation:

What does empty mean?

First of all, we must agree on what empty means. Do you mean to filter out:

How do you filter out the values

To filter out empty strings only:

To only filter out strictly false values, you must use a callback function:

Third and fourth case are (for our purposes at last) equivalent, and for that all you have to use is the default:

php array remove empty values. Смотреть фото php array remove empty values. Смотреть картинку php array remove empty values. Картинка про php array remove empty values. Фото php array remove empty values

For multidimensional array

php array remove empty values. Смотреть фото php array remove empty values. Смотреть картинку php array remove empty values. Картинка про php array remove empty values. Фото php array remove empty values

I had to do this in order to keep an array value of (string) 0

php array remove empty values. Смотреть фото php array remove empty values. Смотреть картинку php array remove empty values. Картинка про php array remove empty values. Фото php array remove empty values

php array remove empty values. Смотреть фото php array remove empty values. Смотреть картинку php array remove empty values. Картинка про php array remove empty values. Фото php array remove empty values

I use the following script to remove empty elements from an array

Just want to contribute an alternative to loops. also addressing gaps in keys.

In my case I wanted to keep sequential array keys when the operation was complete (not just odd numbers, which is what I was staring at. Setting up code to look just for odd keys seemed fragile to me and not future-friendly.)

The combination of array_filter and array_slice does the trick.

No idea on efficiencies or benchmarks but it works.

php array remove empty values. Смотреть фото php array remove empty values. Смотреть картинку php array remove empty values. Картинка про php array remove empty values. Фото php array remove empty values

Just one line : Update (thanks to @suther):

output

php array remove empty values. Смотреть фото php array remove empty values. Смотреть картинку php array remove empty values. Картинка про php array remove empty values. Фото php array remove empty values

php array remove empty values. Смотреть фото php array remove empty values. Смотреть картинку php array remove empty values. Картинка про php array remove empty values. Фото php array remove empty values

use array_filter function to remove empty values:

php array remove empty values. Смотреть фото php array remove empty values. Смотреть картинку php array remove empty values. Картинка про php array remove empty values. Фото php array remove empty values

php array remove empty values. Смотреть фото php array remove empty values. Смотреть картинку php array remove empty values. Картинка про php array remove empty values. Фото php array remove empty values

Remove empty array elements

I think array_walk is much more suitable here

Output:

We made sure that empty values are removed even if the user adds more than one space

We also trimmed empty spaces from the valid values

Finally, only (null), (Boolean False) and (») will be considered empty strings

As for False it’s ok to remove it, because AFAIK the user can’t submit boolean values.

php array remove empty values. Смотреть фото php array remove empty values. Смотреть картинку php array remove empty values. Картинка про php array remove empty values. Фото php array remove empty values

As per your method, you can just catch those elements in an another array and use that one like follows,

php array remove empty values. Смотреть фото php array remove empty values. Смотреть картинку php array remove empty values. Картинка про php array remove empty values. Фото php array remove empty values

try this ** **Example

php array remove empty values. Смотреть фото php array remove empty values. Смотреть картинку php array remove empty values. Картинка про php array remove empty values. Фото php array remove empty values

With these types of things, it’s much better to be explicit about what you want and do not want.

It will help the next guy to not get caught by surprise at the behaviour of array_filter() without a callback. For example, I ended up on this question because I forgot if array_filter() removes NULL or not. I wasted time when I could have just used the solution below and had my answer.

Also, the logic is language angnostic in the sense that the code can be copied into another language without having to under stand the behaviour of a php function like array_filter when no callback is passed.

In my solution, it is clear at glance as to what is happening. Remove a conditional to keep something or add a new condition to filter additional values.

Another benefit of this approach is that you can break apart the filtering predicates into an abstract function that filters a single value per array and build up to a composable solution.

See this example and the inline comments for the output.

Now you can dynamically create a function called filterer() using pipe() that will apply these partially applied functions for you.

Источник

PHP array delete by value (not key)

I have a PHP array as follows:

I’m looking for the simplest function to perform this task, please.

20 Answers 20

The if() statement will check whether array_search() returned a value, and will only perform an action if it did.

Well, deleting an element from array is basically just set difference with one element.

It generalizes nicely, you can remove as many elements as you like at the same time, if you want.

Disclaimer: Note that my solution produces a new copy of the array while keeping the old one intact in contrast to the accepted answer which mutates. Pick the one you need.

One interesting way is by using array_keys() :

The array_keys() function takes two additional parameters to return only keys for a particular value and whether strict checking is required (i.e. using === for comparison).

This can also remove multiple array items with the same value (e.g. [1, 2, 3, 3, 4] ).

If you know for definite that your array will contain only one element with that value, you can do

If, however, your value might occur more than once in your array, you could do this

Note: The second option only works for PHP5.3+ with Closures

php array remove empty values. Смотреть фото php array remove empty values. Смотреть картинку php array remove empty values. Картинка про php array remove empty values. Фото php array remove empty values

php array remove empty values. Смотреть фото php array remove empty values. Смотреть картинку php array remove empty values. Картинка про php array remove empty values. Фото php array remove empty values

Or simply, manual way:

This is the safest of them because you have full control on your array

php array remove empty values. Смотреть фото php array remove empty values. Смотреть картинку php array remove empty values. Картинка про php array remove empty values. Фото php array remove empty values

Output

Array ( [0] => 312 [1] => 1599 [2] => 3 )

With PHP 7.4 using arrow functions:

To keep it a non-associative array wrap it with array_values() :

Explanation: Delete the element that has the key 401 after flipping the array.

php array remove empty values. Смотреть фото php array remove empty values. Смотреть картинку php array remove empty values. Картинка про php array remove empty values. Фото php array remove empty values

To delete multiple values try this one:

php array remove empty values. Смотреть фото php array remove empty values. Смотреть картинку php array remove empty values. Картинка про php array remove empty values. Фото php array remove empty values

The accepted answer converts the array to associative array, so, if you would like to keep it as a non-associative array with the accepted answer, you may have to use array_values too.

Borrowed the logic of underscore.JS _.reject and created two functions (people prefer functions!!)

array_reject_value: This function is simply rejecting the value specified (also works for PHP4,5,7)

array_reject: This function is simply rejecting the callable method (works for PHP >=5.3)

So in our current example we can use the above functions as follows:

or even better: (as this give us a better syntax to use like the array_filter one)

The above can be used for more complicated stuff like let’s say we would like to remove all the values that are greater or equal to 401 we could simply do this:

Источник

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

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