2

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?

4 Answers 4

2

The right array_filter() approach:

$result = array_filter($arr, function($a){ return $a['title']; });
Sign up to request clarification or add additional context in comments.

Comments

1

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 of 0 (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' );

1 Comment

for user contributed notes +1
0

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.

Comments

0

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]);
    }
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.