problem with array returning.

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
itsmani1
Forum Regular
Posts: 791
Joined: Mon Sep 29, 2003 2:26 am
Location: Islamabad Pakistan
Contact:

problem with array returning.

Post 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.
User avatar
itsmani1
Forum Regular
Posts: 791
Joined: Mon Sep 29, 2003 2:26 am
Location: Islamabad Pakistan
Contact:

Post by itsmani1 »

its solved, i wasn't incrementing J var.
User avatar
Jenk
DevNet Master
Posts: 3587
Joined: Mon Sep 19, 2005 6:24 am
Location: London

Post 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;
Post Reply