Page 1 of 1

sizeOf and count [SOLVED]

Posted: Fri Aug 12, 2011 6:03 pm
by PHP_mySQL__Newbie
Hi there,
I am new to PHP code and to this forum. I am looking forward to a great learning experience. I am expecting that the moderator or other members will guide me if I am posting in the wrong forum. Thank you

Newbie

My Question:

I am not able to understand how sizeOf works. Why is sizeOf($row) equal to 6 instead of 3?

Code: Select all

Table:
field1	field2	field3
10	20	ab
11	21	cd
12	22	ef
12	12	gh
Code:

Code: Select all

        <?php
        $conn = mysql_connect("localhost", "x", "y") or die(mysql_error());
        mysql_select_db("db1", $conn) or die(mysql_error());
        
        $sql = "        
            SELECT field1, field2, field3
            From testtable1;
        ";
        $result = mysql_query($sql, $conn) or die(mysql_error());
        $row = mysql_fetch_array( $result );

//      for ($i=0;$i<sizeof($row);$i++)
        for ($i=0;$i<3;$i++)
        {
            echo $row[$i]." ";
        }
        echo "<br>";
        echo sizeof($row); 
        echo "<br>";
        echo count($row);        
        echo "<br>";
        print_r(array_count_values($row));
                
        ?>
Output:

Code: Select all

10 20 ab 
6
6
Array ( [10] => 2 [20] => 2 [ab] => 2 )

Re: sizeOf and count

Posted: Fri Aug 12, 2011 6:59 pm
by Christopher
Try:

Code: Select all

      $n = count($row);
        for ($i=0;$i<$n;$i++)
        {
            echo $row[$i]." ";
        }
        echo "<br>";
        echo sizeof($row); 
        echo "<br>";
        echo count($row);        
        echo "<br>";
        print_r($row);
Remember that associative array in PHP have both string keys and zero based numeric keys.

Re: sizeOf and count

Posted: Fri Aug 12, 2011 11:21 pm
by Weirdan
Remember that associative array in PHP have both string keys and zero based numeric keys.
Generally it's not true, however with the array that mysql_fetch_array() returns it is.

PHP_mySQL__Newbie, run the following code and the issue would be immediately obvious to you:

Code: Select all

<?php
$conn = mysql_connect("localhost", "x", "y") or die(mysql_error());
mysql_select_db("db1", $conn) or die(mysql_error());
        
$sql = "        
     SELECT field1, field2, field3
     From testtable1;
";
$result = mysql_query($sql, $conn) or die(mysql_error());
$row = mysql_fetch_array( $result );
var_dump($row);
PHP Manual wrote: The type of returned array depends on how result_type is defined. By using MYSQL_BOTH (default), you'll get an array with both associative and number indices.