Page 1 of 1

problem with array returning.

Posted: Thu Jun 29, 2006 4:18 am
by itsmani1

Code: Select all

function sorted_votes($myaverage)
	{
		$myarray = array();
		$uarray = array();
		$i = 0;
		$j = 0;
		$res = mysql_query("select * from votes") or die(mysql_error());
		while($row = mysql_fetch_object($res))
		{
			$mycnt = (($row -> cnt)/$myaverage);
			$myarray[$i] = $mycnt;
			$i = $i + 1;
		}
		sort($myarray);
		foreach ($myarray as $key => $val) 
		{
			$uarray[$j] = $val;
		}
		return $uarray;
	}


	$myaverage = total();
	$myarr = array();
	$myarr = sorted_votes($myaverage);
	echo $myarr[2];             // this is not giving me the output.
every thing in the above code is working except one problem and that is of last line, its not giving me output.

when is try sorted_votes() its works fine but after returning it dont' show the result.

any help?

thanks.

Posted: Thu Jun 29, 2006 4:22 am
by itsmani1
its solved, i wasn't incrementing J var.

Posted: Thu Jun 29, 2006 4:25 am
by Jenk
$j is never incremented in any part of your function, thus $uarray will only ever have one indice ($uarray[0]) which will contain whatever the latest value of $val will be.

Therefore when you assign the return value of the function to $myarr, it too will only contain one idice with the the key '0'

:)

Either change to:

Code: Select all

foreach ($myarray as $key => $val) 
                { 
                        $uarray[$j++] = $val; 
                } 
                return $uarray;
or:

Code: Select all

foreach ($myarray as $key => $val) 
                { 
                        $uarray[] = $val; 
                } 
                return $uarray;