1

I have an array like this i want to remove the last array which does not have any values

i used array-filter but its not filtering the array after filter it should

get 0,1,2 only .

$res_arr= array(
    0=>array(1,2,3,6,7),
    1=>array(7,5,3,8),
2=>array(6,5,9,8),
3=>array(),
);

$array1=array();

foreach($res_arr as $array_key=>$array_item)
{
  if($array1[$array_key] == 0)
  {
    unset($array1[$array_key]);
  }
}

 print_r($array1);

Above code i get Undefined offset: 0 Undefined offset: 1 Undefined offset: 2

2
  • what is your $array1 values? Commented Feb 8, 2014 at 8:47
  • 1
    $array1 is empty, there're no elements and this causes warnings Commented Feb 8, 2014 at 8:50

2 Answers 2

4

Using array_filter:

$res_arr= array(
    0=>array(1,2,3,6,7),
    1=>array(7,5,3,8),
    2=>array(6,5,9,8),
    3=>array(),
);
$r = array_filter($res_arr, function($v) { return !empty($v); });
print_r($r);
Sign up to request clarification or add additional context in comments.

Comments

2

Short-cut method.

$new_arr=array_filter($res_arr,'count');
print_r($new_arr);

Demo


The long way..

You could so something like this

<?php
$res_arr= array(
    0=>array(1,2,3,6,7),
    1=>array(7,5,3,8),
    2=>array(6,5,9,8),
    3=>array(),
);

$i=0;
foreach($res_arr as $arr)
{
    if(count($arr)==0)
    {
        unset($res_arr[$i]);
    }
    $i++;
}
print_r($res_arr);

OUTPUT :

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

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

    [2] => Array
        (
            [0] => 6
            [1] => 5
            [2] => 9
            [3] => 8
        )

)

1 Comment

foreach allows you to dynamically access the keys of an array, doing so manually seems downright foolish.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.