John Davidson

php - Remove/Filter rows from array which contain a zero

0 comments
Message:


I have an array of non-empty arrays which contain non-negative integers and I need to remove all rows/subarrays which contain at least one zero.


I know I can use a foreach() or array_filter() to make iterated calls of in_array(), but is there a more elegant/concise approach -- perhaps a functional approach without an anonymous callback?


foreach ($array as $k => $row) {
if (in_array(0, $row)) {
unset($array[$k]);
}
}

Or


array_filter(
$array,
function($row) {
return !in_array(0, $row);
}
)

Sample array:


$array = [
'one' => [20,0,40,0,60],
'two' => [50],
'three' => [0, 0, 0, 0],
'four' => [10, 5],
'five' => [0],
];

Desired output:


['two' => [50], 'four' => [10, 5]]


My Answer:
> You can use the `array_filter()` function with a custom callback function to achieve this in a more concise way without using an anonymous callback. Here's an example:

php
$array = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[0, 1, 2],
[3, 0, 4]
];

function hasZero($subarray) {
return !in_array(0, $subarray);
}

$result = array_filter($array, 'hasZero');

print_r($result);


This will output:


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

[1] => Array
(
[0] => 4
[1] => 5
[2] => 6
)

[2] => Array
(
[0] => 7
[1] => 8
[2] => 9
)

)


This code defines a custom function `hasZero()` that checks if a subarray contains a zero. The `array_filter()` function then filters out the subarrays that return `false` from the `hasZero()` function.

Rate this post

4 of 5 based on 8847 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us