Jump to content


Photo

why does the sizeof and count give incorrect array size?


  • Please log in to reply
5 replies to this topic

#1 Synergic

Synergic
  • Members
  • PipPip
  • Member
  • 21 posts

Posted 14 August 2006 - 10:51 AM

why do both these functions:


sizeof -- Alias of count()
count -- Count elements in an array, or properties in an object

give an array size of 1 even though there's nothing inside it?
I then add something to it and it gives me 1 still then 2. what is in index 0? i need to do some manipulation and have to check if an array is empty.

#2 Chetan

Chetan
  • Members
  • PipPipPip
  • Advanced Member
  • 162 posts
  • LocationIndia

Posted 14 August 2006 - 11:04 AM

Gives me 0 if empty, it dosent give me 1.
And if it is a variable then ofcource it gives 1.
I am a PHP Guru, ask me questions if you want to

#3 Synergic

Synergic
  • Members
  • PipPip
  • Member
  • 21 posts

Posted 14 August 2006 - 11:33 AM

yeah but if i add something to the array it gives me 1. It's hard to tell if its really empty or not...

#4 AndyB

AndyB
  • Staff Alumni
  • Advanced Member
  • 5,465 posts
  • LocationToronto

Posted 14 August 2006 - 11:34 AM

The answer is in the manual - http://ca.php.net/ma...ction.count.php

count() may return 0 for a variable that isn't set, but it may also return 0 for a variable that has been initialized with an empty array. Use isset() to test if a variable is set.


Legend has it that reading the manual never killed anyone.
My site

#5 Synergic

Synergic
  • Members
  • PipPip
  • Member
  • 21 posts

Posted 14 August 2006 - 11:54 AM

<? if (isset($_SESSION['cart']))
{
	echo 'Array is set.';
} ?>

<?echo '<pre>';
   print_r( $_SESSION ); 
echo '</pre>';?>

result:

Array is set

Array
(
    [cart] => ShoppingCartClass Object
        (
            [items] => Array
                (
                )

            [totalPrice] => 
        )

)

what gives?  :-\

#6 Synergic

Synergic
  • Members
  • PipPip
  • Member
  • 21 posts

Posted 14 August 2006 - 12:52 PM

ok fixed, the problem was 'cart' was an object i got confused with 'it' being an array. I accessed the array inside cart which is items and recieve a 0 :)




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users