Remove Zero Values from a PHP Array

Remove zero values from a PHP array

array_filter does that. If you don’t supply a callback function, it filters all values out that equal false (boolean conversion).

PHP remove entry if array value equals to 0

foreach to the rescue:

foreach($arr as $key => $entry) {
if(isset($entry[1]) && $entry[1] === 0) {
unset($arr[$key]);
}
}

And an array_filter example:

$arr = array_filter($arr, function($entry) {
return $entry[1] !== 0;
});

(assumes at least php 5.3, though you can get around that by creating a named function and passing that as the second parameter to array_filter)

Remove/Filter rows from array which contain a zero

In all honesty, I think that PHP7.4's arrow function syntax makes the array_filter() call reasonably concise.

array_filter($array, fn($row) => !in_array(0, $row))

Additionally, iterated calls of !in_array() with a true third parameter can distinguish between different types and ensure that only integer-typed zeros are targeted. (Demo)

array_filter($array, fn($row) => !in_array(0, $row, true))

That said, because you have non-empty subarrays, you can use array_product as the callback name. By multiplying all values in a respective row together, any row containing a zero will result in 0. Since 0 is a falsey value, array_filter() will exclude the row from the result array. This approach will work even if there are floats or negative numbers in the subarrays. Be aware that array_product() will not remove empty rows/subarrays.

Code: (Demo)

var_export(
array_filter($array, 'array_product')
);

Output:

array (
'two' =>
array (
0 => 50,
),
'four' =>
array (
0 => 10,
1 => 5,
),
)

For the slightly altered behavior of only keeping rows that contain at least one non-zero value, array_sum can be used in the same fashion. This approach will still work with empty subarrays or subarrays containing floats, but should not be trusted if a mix of negative and positive values in a respective subarray is possible. (Demo)

var_export(
array_filter($array, 'array_sum')
);

Output:

array (
'one' =>
array (
0 => 20,
1 => 0,
2 => 40,
3 => 0,
4 => 60,
),
'two' =>
array (
0 => 50,
),
'four' =>
array (
0 => 10,
1 => 5,
),
)

Removing all zeros from an array

There are a few related approaches, split into two camps. You can either use a vectorised approach via calculation of a single Boolean array and np.ndarray.all. Or you can calculate the index of the first row which contains only 0 elements, either via a for loop or next with a generator expression.

For performance, I recommend you use numba with a manual for loop. Here's one example, but see benchmarking below for a more efficient variant:

from numba import jit

@jit(nopython=True)
def trim_enum_nb(A):
for idx in range(A.shape[0]):
if (A[idx]==0).all():
break
return A[:idx]

Performance benchmarking

# python 3.6.5, numpy 1.14.3

%timeit trim_enum_loop(A) # 9.09 ms
%timeit trim_enum_nb(A) # 193 µs
%timeit trim_enum_nb2(A) # 2.2 µs
%timeit trim_enum_gen(A) # 8.89 ms
%timeit trim_vect(A) # 3.09 ms
%timeit trim_searchsorted(A) # 7.67 µs

Test code

Setup

import numpy as np
from numba import jit

np.random.seed(0)

n = 120000
k = 1500

A = np.random.randint(1, 10, (n, 3))
A[k:, :] = 0

Functions

def trim_enum_loop(A):
for idx, row in enumerate(A):
if (row==0).all():
break
return A[:idx]

@jit(nopython=True)
def trim_enum_nb(A):
for idx in range(A.shape[0]):
if (A[idx]==0).all():
break
return A[:idx]

@jit(nopython=True)
def trim_enum_nb2(A):
for idx in range(A.shape[0]):
res = False
for col in range(A.shape[1]):
res |= A[idx, col]
if res:
break
return A[:idx]

def trim_enum_gen(A):
idx = next(idx for idx, row in enumerate(A) if (row==0).all())
return A[:idx]

def trim_vect(A):
idx = np.where((A == 0).all(1))[0][0]
return A[:idx]

def trim_searchsorted(A):
B = np.frombuffer(A, 'S12')
idx = A.shape[0] - np.searchsorted(B[::-1], B[-1:], 'right')[0]
return A[:idx]

Checks

# check all results are the same
assert (trim_vect(A) == trim_enum_loop(A)).all()
assert (trim_vect(A) == trim_enum_nb(A)).all()
assert (trim_vect(A) == trim_enum_nb2(A)).all()
assert (trim_vect(A) == trim_enum_gen(A)).all()
assert (trim_vect(A) == trim_searchsorted(A)).all()

How to remove zero values from an array in parallel

To eliminate some elements from an array you may use Thrust Library's reordering operations. Given a predicate is_not_zero, which returns false for zero values, and true for others, you may write the operation like this

thrust::copy_if(in_array, in_array + size, out_array, is_not_zero);

the output array will include only the values which are non-zero, because the predicate indicates so.

You may also use "remove_if" function with a reverse predicate which return true for zeros, and false for others..

thrust::remove_if(in_array, in_array + size, is_zero);

I suggest you taking a look at compaction examples of Thrust library, or general compaction concept.

https://github.com/thrust/thrust/blob/master/examples/stream_compaction.cu

Remove empty array elements

As you're dealing with an array of strings, you can simply use array_filter(), which conveniently handles all this for you:

print_r(array_filter($linksArray));

Keep in mind that if no callback is supplied, all entries of array equal to FALSE (see converting to boolean) will be removed. So if you need to preserve elements that are i.e. exact string '0', you will need a custom callback:

// PHP 7.4 and later
print_r(array_filter($linksArray, fn($value) => !is_null($value) && $value !== ''));

// PHP 5.3 and later
print_r(array_filter($linksArray, function($value) { return !is_null($value) && $value !== ''; }));

// PHP < 5.3
print_r(array_filter($linksArray, create_function('$value', 'return $value !== "";')));

Note: If you need to reindex the array after removing the empty elements, use: $linksArray = array_values(array_filter($linksArray));

remove zero occurrence in array

array_filter ( array $input);

Should work. It will delete all elements with value equals to false.
If you would like all elements that are === 0 create your own callback function for array_filter like in the link below.
http://php.net/manual/en/function.array-filter.php

Remove all zero values from string PHP

here's a nice algo:

<?php

$string = "14522354265300000000000";
$new_string = '';
for($i=0; $i<strlen($string) ; $i++){
if($string[$i] != '0'){
$new_string .= $string[$i];
}
}

echo $new_string;

?>

rtrim is only if you have zero's at end of string :)



Related Topics



Leave a reply



Submit