Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

unable to saved value into global variable

madkrismadkris Posts: 3Member
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..

[code]<?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'] . "
";
}
return $GLOBALS['smallest'];
}
findSmall($array1);
echo '
';
var_dump($GLOBALS['smallest']);//returns null
echo '
';
?>[/code]

Comments

  • tradmtradm Posts: 49Member
    [b]WHY ITS NOT WORKING[/b]

    Logical error
    Change

    [code]for($i = 0; $i < $size; $i++)[/code]
    to
    [code]for($i = 0; $i < $size - 1; $i++)[/code]

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

    Syntax Error

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


    [b]TIP[/b]

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

    [code]$smallest = min($array1);[/code]

    Hope it helps.
  • madkrismadkris Posts: 3Member
    Been away for sometime, was able to fix my problem. just wanted thank you nonetheless for your reply.


Sign In or Register to comment.