SitePoint Sponsor

User Tag List

Page 2 of 4 FirstFirst 1234 LastLast
Results 26 to 50 of 79
  1. #26
    SitePoint Addict
    Join Date
    Dec 2005
    Posts
    336
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    Perhaps these examples can help understand return and true/false statements

    PHP Code:
    <?php

    // Return & Echo
        
    function rtnMyStr$str ) {
            return 
    $str;
        }
            echo 
    rtnMyStr('Hello World<br />');

        function 
    echoMyStr$str ) {
            echo 
    $str;
        }
            
    echoMyStr('Hello World<br />');
        
    // Return within a function    
        
    function numTest$num null ) {
            if( 
    is_null($num) ) return;    
            if( !
    is_int($num) ) {
                return 
    false;
            }
            return 
    true;
        }    

        
    // Function return is identical to boolean false
            
    if( numTest('Five') === FALSE ){
                echo 
    'numTest(\'Five\') is False<br />';
            }
        
    // Function return is true
            
    if( numTest(123) ) {
                echo 
    'numTest(123) is True<br />';
            }

        
    // Empty argument... function returns nothing
        // Nothing gets echo'd
            
    if( numTest() ) {
                echo 
    'numTest() is True<br />';
            }
            if( 
    numTest() === FALSE ) {
                echo 
    'numTest() is False<br />';
            }
            
                
        function 
    checkArray$arr ) {
            
    $isarray False;
            if( 
    is_array($arr) ) {
                
    $isarray TRUE;
            }
            return 
    $isarray;
        }    
        
        
    $a = array(
            
    'a' => array(),
            
    'b' => 'str',
            
    'c' => array(1,2,3)
        );
        foreach( 
    $a as $k => $v ) {
            
    $bool checkArray($v) === TRUE
                
    'True'
                
    'False';
                
            echo 
    'Key '.$k.' is '.$bool.'<br>';
        }
            

    ?>

  2. #27
    SitePoint Enthusiast
    Join Date
    Oct 2007
    Posts
    34
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Ethan-27 View Post
    Thanks Lesley, appreciate your effort.

    Everything you explained has been very helpful but I think you may not have read the previous posts properly as to what Im stuck on.

    PHP Code:
    Originally Posted by Ethan-27 View Post
    It also shows how the user can affect the result returned 
    What I meant to say here is it shows how the users input affect which return is used. This to me makes sense.
    ....

    I'm desperately trying to think of what to say here. ... Data In - Process - Data out ...
    That is what programming is fundamentally about. It doesn't matter if it's procedural , object oriented or functional programming you get some data in from somewhere, process it, and put it back out somehow

    A function is a unit of code that performs a task of some finite unambiguous description, it can be called one or more times by other code.

    A function can be thought of as a mini-program. It takes data in, processes it, and returns data somehow - whether through return values or passing parameters by reference.
    Quote Originally Posted by Ethan-27 View Post

    Regarding the addthese function that comparison was the one I was most proud of. Funnily enough that is the function I understand most. :-)
    The addThese function is a very basic function. It takes three values, (data input), adds them up (processes the data) and then returns the processed data (data output).

    I'm glad to hear you feel you at least understand it.
    Quote Originally Posted by Ethan-27 View Post

    The part about 'challenge', I think I understand.... As explained previously that when echoing just a string, in some cases there is no need to return anything because nothing is really going on (compared to functions that return something) It's kinda like "here it is, dont complicate, nothing in the way, just echo the bloody thing"
    .... Depends what environment you are working in ... echo doesn't return any value to indicate success or failure of echoing the message to a given output device and print, in PHP, always returns 1.

    The language you are using, PHP, doesn't allow you to go any further in checking the print/echo actually worked.

    FWIW the displayError function accepts data, processes it (via the echo call) but doesn't return anything; the processing provides some data output but in a non-interesting way for the computer doing the processing.

    Quote Originally Posted by Ethan-27 View Post

    Its quite obvious my bit of fun confused and I apologise for busying your brain more than needs be ,so Ill try to refrain from that in the future and stick to the php vocab. But believe it or not I am so much more clear now, perhaps not totally correct but alot more clear.
    I felt there was absolutely no way for a native English speaker to work out if you had understood anything at all. I have no idea what it would have been like for someone whose first language is not English. I am glad you can comprehend the humour gets in the way of clarity.
    Quote Originally Posted by Ethan-27 View Post

    I think Im gonna really study some codes this wknd and watch how people use functions in different situations, Im sure itll click soon.
    Like others have said, studying is good, writing your own code is even better. Try and find a good book or website that teaches programming fundamentals along with PHP. Many books that teach programming fundamentals have exercises at the end of each chapter. The exercises are good to work on to confirm your level of understanding. I'm sure there are some good PHP sites out there that work similarly.

    Good luck with your study.

  3. #28
    SitePoint Guru
    Join Date
    Oct 2006
    Location
    Queensland, Australia
    Posts
    852
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I never had any problems grasping functions when I was learning code. I mainly had trouble with statements; do I have to assign everything to a variable? is it legal to just put a number or a string on a line by itself, if so, does anything happen?

    Ethan-27, I'd say in your case understanding functions probably isn't the root problem here, it's likely a symptom of a scewed perspective of programming. Just my two worthless cents.

  4. #29
    Community Advisor silver trophybronze trophy
    dresden_phoenix's Avatar
    Join Date
    Jun 2008
    Location
    Madison, WI
    Posts
    2,791
    Mentioned
    34 Post(s)
    Tagged
    2 Thread(s)
    OK...
    Hopefully this will answer your question. When scripting or coding, A function function to avoid repetition. A function can be use one time, an infinite number of times or not at all. Coders use the term "calling" when they use a function.

    foo($arg){
    if ($arg==0){ return;}
    if ($arg==1){ return false;}
    $modArg=$arg *2;
    return "$modArg is 2x $arg";
    }

    $a= foo(0);// null
    $a =foo(1);// Boolean false
    $a=foo(5);// string "10 is 2x 5"


    1. I can call foo(); as many times as needed.
    2. you will notice I used return 3times in the function. In a function the return statement ESCAPES the function and goes back to executing the code where it was called from.
    3. A "return" by itself does not pass any variable back...$a= foo(0);// null.

    "thats useless", you might say... but remember the function of a function is to keep you from having to type the same code over and over ... So that means you may have OUTPUT FUNCTIONS.. that is functions you use merely to calculate something then ECHO it.

    foo($content $headline, $tag=1){
    echo "<div class='part'><h$tag> $headline</h$tag>$content</div>";
    return;
    }

    you dont really want to send anything back to the main code you just want a variable output....in that example the return is merely a formality.

    when you want something sent back... you use: return $functionvar;
    $functionvar has to be a variable that inside the function. This is for the same reason that if you try to work with a variable from your main code within the function, without having passed it TO the function, by putting it in ().... you will get a variable not declared error. This is know as scope...

    Ok so you sent a vaiable ( actually a copy of a variable) into the function... but you want to get data BACK out... you can send ONE result out of the function. Thats teh other thing return does it sends a variable or constant out...

    return $var; // returns $var to the main code..
    return 15; // returns 15 to the main code..
    return true; // returns boolean true to the main code..

    if you don't have anything to cat the returned result it is lost. No biggie.
    foo(2); // returned value is lost...
    $a=foo(2); // whatever foo calculated is stored in $a

    why not capture values all the time, you say? well thin about it a function can be ANYTHING... its just to keep you from typic code over and over...

    so what if you wanted to check that the result of a value plugged into a formula is not 10, for example...

    foo($agr){
    $mathStuff=$arg/(2*11);
    if ($mathStuff!=10) {return true);}
    return false;}

    if you follow the code... you will see that foo() will return Boolean true for any value that, when divided by 22 doesnt equal 10... and return Boolean false for anything else

    you can use this directly in an if statement in the main code:
    if (foo($argToTest)){ do something...}

    see, a value you didnt need to capture and a use for returning booleans !




    hope that makes things a little clearer

  5. #30
    SitePoint Zealot Ethan-27's Avatar
    Join Date
    Jan 2011
    Posts
    152
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Once again thankyou.

    I've been reading all your examples and all your advice and feel very lucky that so may people have put such an effort into helping me get past this. It really is appreciated.

    I've been working on code all day and am starting to write some small working functions. I'll post them up later this week to see if they are ok.

    Something totally off topic occured to me today, I was just wondering, do functions, if, else statements etc mean the same thing in all programming languages...? Perhaps the syntax is different and some parts might not work the same as with others but is their general nature the same ....?

    Anyways cheer again guys

  6. #31
    SitePoint Wizard
    Join Date
    Jul 2003
    Location
    Kent
    Posts
    1,921
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    Could I suggest another way to think about functions.

    Suppose you have a complex calculation which you will carry out in several different parts of your site / application / whatever. You would write a function to carry out this calculation and return the value to some variable, which you will then use in some other part of your scripts. You might wish to do this on several different pages.

    Perhaps it was the distance in feet between two places give their latitude and longitude.

    So you just call the function whenever you need to do this calculation on a particular page, pass the values to work with to the function, and out comes the answer.

    You wouldn't know the answer until you passed the values to the function.

    The examples given to help you are usually a bit simple so you can see what is happening. But writing 10 or 20 lines of a calculation once is much better than having to copy and paste these lines, then fiddle with them to put the values you want used in the right place.


    But suppose you only needed to do this calculation once on your entire web site or application - why bother to write a function, just do the calculation in normal procedural code.

  7. #32
    SitePoint Zealot Ethan-27's Avatar
    Join Date
    Jan 2011
    Posts
    152
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hey again guys, been reading up and today Ive written two functions that are really simple and both work.

    PHP Code:
    function basic_prg (&$sum){ 

    $sum $sum *10;

    }

    $number1 15;

    basic_prg($number1);

    echo 
    "$number1  <br/>"


    function 
    adding(){
        
    global 
    $moves;

    $moves $moves 10;

    }
    $moves 15;
    adding();
    echo 
    "$moves <br/>"
    As you can see they both do the same thing (equal 150) just one using local and one using global scope.

    This next function I have written is trying to grab the returned result of the second function (adding) and echo a string back if it is an integer and is not empty. The $moves variable is global.

    PHP Code:
    function check_rtn ($moves);

    if (
    is_int($moves)) && ($moves !=' '){
    return 
    true;
    }
    echo 
    "Yes yes it's a number and you caught it!"
    I haven't actually referenced the function (adding), only the global variable used in it's code, I'm sure this is part of where Im going wrong.

  8. #33
    SitePoint Addict
    Join Date
    Dec 2005
    Posts
    336
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    There are a few errors in the last function:

    1. The function needs an opening and closing bracket, not the semi-colon that is present.
    2. This line:
    PHP Code:
    if (is_int($moves)) && ($moves !=' '){ 
    Should be:
    PHP Code:
    if( is_int($moves) && $moves !=' ' ){ 
    Also, i am thinking there may be a logic error here too. You probably want to check if $moves is empty before you do the addition, not afterwards, because it was always evaluate to an integer (ie nothing * anyNumber = 0). At that point, you would just need an is_int check:
    PHP Code:
    if( is_int($moves) ) {
        echo 
    "Yes yes it's a number and you caught it!"


  9. #34
    SitePoint Zealot Ethan-27's Avatar
    Join Date
    Jan 2011
    Posts
    152
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Cheers for clearing that code up, it still not showing the string though.

    I noticed you didn't include the return statement , I tried it with and without, still no luck.

    So for the function to recognise that the previous function returned a result (hence displaying the echo) I dont need to reference the function (adding)...? Is that because the variable I am using is global...?

  10. #35
    Community Advisor silver trophybronze trophy
    dresden_phoenix's Avatar
    Join Date
    Jun 2008
    Location
    Madison, WI
    Posts
    2,791
    Mentioned
    34 Post(s)
    Tagged
    2 Thread(s)
    you have to pass the variables to each other... or sues them in some way. Right now your code has all of the functions being unrelated to each other! BTW, globalizing variables.. is kinda heavy handed.

    Code:
    // stick all the function together in the code, doesnt change the way they work but it's easier to read///
    
    function=basic_prg (&$sum){ 
    $sum = $sum*10;
    return $sum; 
    }
    
    function adding(){
    global $moves;
    $moves  = $moves *10;
    }
    
    function check_rtn($moves){
    if (is_int($moves)) && ($moves!=' '){return true;}
    return false;
    }
    
    
    $number1 = 15;
    echo basic_prg($number1)."<br/>";
    
    
    $moves = 15;
    adding();
    echo "$moves <br/>"; 
    
    if check_rtn ($moves){ echo "Yes yes it's a number and you caught it!"; }// calls the function and acts according to the RETURNED result

  11. #36
    SitePoint Zealot Ethan-27's Avatar
    Join Date
    Jan 2011
    Posts
    152
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks for writing that mate. :-)

    Little bit confused though why the string could not just be echoed after the code of that function rather than writing another "if" statement... is there not a way to do that...?

    May I also ask why you returned both 'true' and 'false' in the 3rd function...?

  12. #37
    From Italy with love silver trophybronze trophy
    guido2004's Avatar
    Join Date
    Sep 2004
    Posts
    9,495
    Mentioned
    161 Post(s)
    Tagged
    4 Thread(s)
    Quote Originally Posted by Ethan-27 View Post
    Little bit confused though why the string could not just be echoed after the code of that function rather than writing another "if" statement... is there not a way to do that...?
    Yes, echo the string in the function, without returning TRUE or FALSE.
    If however your funtion returns TRUE or FALSE, and you want to echo the string only when the function returns TRUE, you'll have to tell that to the PHP parser. Otherwise, how would he know? Guess?

  13. #38
    From Italy with love silver trophybronze trophy
    guido2004's Avatar
    Join Date
    Sep 2004
    Posts
    9,495
    Mentioned
    161 Post(s)
    Tagged
    4 Thread(s)
    You are missing a closing bracket, you close the if, but not the function.

    Anyway, once resolved that error, I predict that you'll still not see that string

    And please, to understand the way functions work, put them all on top of your script like dresden_phoenix has done in his post, and leave only the function calls where they are right now (that is: at the point in the script where you need to call them).

  14. #39
    SitePoint Zealot Ethan-27's Avatar
    Join Date
    Jan 2011
    Posts
    152
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Cheers that worked :-). I can now see the echo!!!
    I'll also follow the instruction of putting the functions at the top now

    The example given by phoenix (thankyou) I can't get to work though. I just keeps getting syntax errors that I can't see...?

  15. #40
    From Italy with love silver trophybronze trophy
    guido2004's Avatar
    Join Date
    Sep 2004
    Posts
    9,495
    Mentioned
    161 Post(s)
    Tagged
    4 Thread(s)
    Quote Originally Posted by Ethan-27 View Post
    Cheers that worked :-)
    What happened to your post though? Did you delete it?
    The example given by phoenix (thankyou) I can't get to work though. I just keeps getting syntax errors that I can't see...?
    You can't see? Then how do you know they're syntax errors?

  16. #41
    SitePoint Zealot Ethan-27's Avatar
    Join Date
    Jan 2011
    Posts
    152
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by guido2004 View Post
    What happened to your post though? Did you delete it?

    You can't see? Then how do you know they're syntax errors?

    Yeh I deleted the first reply because as soon as I pasted it on here I saw the problem.

    I gotta be more clear. I'm using DreamWeaver and everytime the syntax is wrong it highlights. So visually I can see it but the part of my brain that should be able to figure it out can't.

    EDIT. This is driving me mad , now when I try to run the echo I can't see it, but it worked before!!!

  17. #42
    From Italy with love silver trophybronze trophy
    guido2004's Avatar
    Join Date
    Sep 2004
    Posts
    9,495
    Mentioned
    161 Post(s)
    Tagged
    4 Thread(s)
    Quote Originally Posted by Ethan-27 View Post
    EDIT. This is driving me mad , now when I try to run the echo I can't see it, but it worked before!!!
    Quote Originally Posted by guido2004 View Post
    Anyway, once resolved that error, I predict that you'll still not see that string
    I told you...
    You wrote a function to display the string, but you never call it anywhere (at least not in the code in the post you deleted).

  18. #43
    SitePoint Zealot Ethan-27's Avatar
    Join Date
    Jan 2011
    Posts
    152
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by guido2004 View Post
    I told you...
    You wrote a function to display the string, but you never call it anywhere (at least not in the code in the post you deleted).
    lol yes you were right

    The reason it worked the first time is because I placed the echo outside the function. Ive come up with this and it seems to work.

    PHP Code:

    function check_rtn ($moves){

    if (
    is_int($moves) && $moves !='');

    echo 
    "Yes yes it's a number and you caught it";
    }
        
    echo 
    check_rtn($moves); 
    I need a drink.

  19. #44
    From Italy with love silver trophybronze trophy
    guido2004's Avatar
    Join Date
    Sep 2004
    Posts
    9,495
    Mentioned
    161 Post(s)
    Tagged
    4 Thread(s)
    It does?
    Code:
    if (is_int($moves) && $moves !='');
    What is that ; doing there?

  20. #45
    SitePoint Zealot Ethan-27's Avatar
    Join Date
    Jan 2011
    Posts
    152
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    mmm not sure, anyway it's not in the original code so all's working with that one.

    I still don't really understand the other example but that will give me something to work on tonight..

    Cheers Guido

  21. #46
    SitePoint Wizard silver trophybronze trophy Stormrider's Avatar
    Join Date
    Sep 2006
    Location
    Nottingham, UK
    Posts
    3,133
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    That won't work at all. The echo will be run in all cases, the if is basically doing nothing.

  22. #47
    SitePoint Zealot Ethan-27's Avatar
    Join Date
    Jan 2011
    Posts
    152
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    When I comment out the echo, the string isn't displayed

    PHP Code:
    function check_rtn ($moves){

    if (
    is_int($moves) && $moves !='')

    echo 
    "Yes yes it's a number and you caught it";
    }
        

    //echo check_rtn($moves); 

    However when I don't comment it out the string is displayed.


    PHP Code:
    function check_rtn ($moves){

    if (
    is_int($moves) && $moves !='')

    echo 
    "Yes yes it's a number and you caught it";
    }
        
    echo 
    check_rtn($moves); 

  23. #48
    From Italy with love silver trophybronze trophy
    guido2004's Avatar
    Join Date
    Sep 2004
    Posts
    9,495
    Mentioned
    161 Post(s)
    Tagged
    4 Thread(s)
    Code:
    echo check_rtn($moves);
    What are you echoing here? That function doesn't return anything. The string is already echoed in the function.

  24. #49
    SitePoint Wizard silver trophybronze trophy Cups's Avatar
    Join Date
    Oct 2006
    Location
    France, deep rural.
    Posts
    6,869
    Mentioned
    17 Post(s)
    Tagged
    1 Thread(s)
    Quote Originally Posted by Ethan-27 View Post
    When I comment out the echo, the string isn't displayed
    PHP Code:
    //echo check_rtn($moves); 
    This below is an example of commenting out the echo ...

    PHP Code:
    //echo 
    check_rtn($moves); 
    ... but just leaving the call.

  25. #50
    SitePoint Zealot Ethan-27's Avatar
    Join Date
    Jan 2011
    Posts
    152
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    But the string doesn't show unless the second echo (the one outside the function) is there.

    I am using this with my other functions which both show "150" in the browser.

    EDIT I've just noticed what Im doing. I tried just calling the function rather than echoing it and got the same result. No need to put echo


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •