Howdy, Stranger!

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

Categories

Welcome to the new platform of Programmer's Heaven! We apologize for the inconvenience caused, if you visited us from a broken link of the previous version. The main reason to move to a new platform is to provide more effective and collaborative experience to you all. Please feel free to experience the new platform and use its exciting features. Contact us for any issue that you need to get clarified. We are more than happy to help you.

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.