Reputation: 3414
I have an array like :
Array
(
[0] => Array
(
[id] => 1367
[category_value] => 15
[isepisode] => 0
[title] => hello world
)
[1] => Array
(
[id] => 9892
[category_value] =>
[isepisode] => 0
[title] =>
)
[2] => Array
(
[id] => 9895
[category_value] =>
[isepisode] => 0
[title] => Bla Bla
)
)
I want to remove array those title
is empty.
Here is my code:
$res = array_map('array_filter', $data);
print_r(array_filter($res)); exit;
Above code only removing those array values are empty. But I want to remove whole array which title is null. My output should be:
Array
(
[0] => Array
(
[id] => 1367
[category_value] => 15
[isepisode] => 0
[title] => hello world
)
[2] => Array
(
[id] => 9895
[category_value] =>
[isepisode] => 0
[title] => Bla Bla
)
)
Note: I have thousands of array. If put foreach this will take time to execute. Is there any easiest way to do that?
Upvotes: 2
Views: 58
Reputation: 1477
If you want to do this using foreach()
try something like this:
$array = array(array('id'=>1,'title'=>'john'),array('id'=>2,'title'=>''),array('id'=>3,'title'=>'mike'));
foreach($array as $key => $val){
if($val['title']==''){
unset($array[$key]);
}
}
Upvotes: 0
Reputation: 13083
You can make use of callback argument in array_filter
. For example:
$result = array_filter($data, function($entry) {
return ! empty($entry['title']);
});
print_r($result);
Better yet, if you check the user contributed notes section of the docs, you can see:
If you want a quick way to remove
NULL
,FALSE
and Empty Strings (""), but leave values of0
(zero), you can use the standard php function strlen as the callback function:e.g.:
<?php // removes all NULL, FALSE and Empty Strings but leaves 0 (zero) values $result = array_filter( $array, 'strlen' );
Upvotes: 1
Reputation: 72226
You can use array_filter()
with a custom callback function that implements your filtering rule:
$res = array_filter
$data,
function (array $item) {
return strlen($item['title']);
}
);
The callback function returns 0
for the items whose title
is the empty string (or NULL
). array_filter()
removes these entries from the provided array.
Upvotes: 0
Reputation: 92854
The right array_filter()
approach:
$result = array_filter($arr, function($a){ return $a['title']; });
Upvotes: 2