Jump to content

Recommended Posts

Hi.

 

 

echo '<pre>'. print_r($items, true).'</pre>'; 

The statement above returns the following array:

Array

(

    [1] => 325

    [2] => 326

    [3] => 327

    [4] =>

    [5] =>

    [6] =>

    [7] =>

    [8] =>

    [9] =>

    [10] =>

    [11] =>

    [12] =>

)

 

echo COUNT($items) 

 

returns: 12

 

The count should be 3 not 12. How can I exclude the empty array?

 

thanks

Link to comment
https://forums.phpfreaks.com/topic/198138-count-function-returns-wrong-count/
Share on other sites

I want to be able to quickly do a loop using a simple count like this:

for($i = 0; $i < count($items); $i++) {
// do things here. 
}

 

I tried using the unset() function but it does not seem to do anything.

for($j=1; $j <= count($items); $j++){
  if($items[$j]==NULL){
  unset($items[$j]);
}
}

 

There has to be an easy way to do this.

$item_count = 0;
while (list($key, $value) = each($items)) {
                if ($value) {
                        $item_count++;
                }
        }

for($i = 0; $i < $item_count; $i++) {
    // do things here. 
} 

$i = 0;
foreach($items as $key => $value) {
  if(!empty($value)) { $i++; }
}

 

To create an new array, do this:

 

foreach($items as $key => $value) {
  if(!empty($value)) { 
    $newArray[] = $value;
  }
}

 

$i will have your total. You may also want to look into why your array is getting NULL values entered into it as well...

 

 

I'm generally not a fan of looping through the array that many times when you don't need the empty values. Or, just remove the empty ones first:

<?php
function clearEmptyValues ($arr) {
     $newarr = array();
     foreach ($arr as $key => $val) {
          if (!empty($v)) $newarr[$key] = $val;
     }
     return $newarr;
}

 

Then:

$items = clearEmptyValues($items);

$count = count($items);

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.