PHP

Moderators: None (Apply to moderate this forum)
Number of threads: 1848
Number of posts: 5016

This Forum Only
Post New Thread
Single Post View       Linear View       Threaded View      f

Report
unable to saved value into global variable Posted by madkris on 20 Jun 2009 at 6:44 PM
hi, im new to php and was trying to do a sort on an array without using the predefined ones, everything else seems to be working except for this part..
was hoping you guys could help me out. thanks in advance..

<?php
$array1 = array(4,8,2,7,1);
$smallest;

//find smallest value in array
function findSmallest($array){
   $size = count($array);
   $GLOBALS['smallest'] = $array[0];
   for($i = 0; $i < $size; $i++) {
      if($GLOBALS['smallest'] > $array[$i+1]){
         $GLOBALS['smallest'] = $array[$i+1];            
      }
      //echo $GLOBALS['smallest'] . "<br>";
   }   
   return $GLOBALS['smallest'];                
}
findSmall($array1);
echo '<pre>';
      var_dump($GLOBALS['smallest']);//returns null
echo '</pre>';
?>

Report
Re: unable to saved value into global variable Posted by tradm on 22 Jun 2009 at 12:46 AM
WHY ITS NOT WORKING

Logical error
Change

for($i = 0; $i < $size; $i++)

to
for($i = 0; $i < $size - 1; $i++)


You will be able to figure out why. I guess :)

Syntax Error

You are calling function findSmall($array1) instead of findSmallest($array1);


TIP

You can use min() function to get the minimum element in an array
eg

$smallest = min($array1);


Hope it helps.
Report
Re: unable to saved value into global variable Posted by madkris on 6 Jul 2009 at 8:10 PM
Been away for sometime, was able to fix my problem. just wanted thank you nonetheless for your reply.





 

Recent Jobs

Official Programmer's Heaven Blogs
Web Hosting | Browser and Social Games | Gadgets

Popular resources on Programmersheaven.com
Assembly | Basic | C | C# | C++ | Delphi | Flash | Java | JavaScript | Pascal | Perl | PHP | Python | Ruby | Visual Basic
© Copyright 2011 Programmersheaven.com - All rights reserved.
Reproduction in whole or in part, in any form or medium without express written permission is prohibited.
Violators of this policy may be subject to legal action. Please read our Terms Of Use and Privacy Statement for more information.
Operated by CommunityHeaven, a BootstrapLabs company.