Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 4 of 4
  1. #1
    Regular Coder
    Join Date
    Feb 2005
    Posts
    663
    Thanks
    5
    Thanked 14 Times in 14 Posts

    echo function variable

    I'm trying to learn more about functions, how they work, etc, and have a quick, hopefully easy question.

    How do you possibly echo a specific variable from function? In experimenting, I tried the below simple code, but no luck with it.
    PHP Code:
    function lets_learn(){
        
    $a 'variable_a';
        
    $b 'variable_b';
    }
    $a lets_learn($a);
    $b lets_learn($b);

    echo 
    $b

  • #2
    Senior Coder Nightfire's Avatar
    Join Date
    Jun 2002
    Posts
    4,265
    Thanks
    6
    Thanked 48 Times in 48 Posts
    Can only return 1 variable from a function (from what I've experienced anyway). This is what you'll have to do.

    PHP Code:
    function lets_learn($which){
        if(
    $which == 'a'){
           
    $var 'variable_a';
        }else{
           
    $var 'variable_b';
        }

    return 
    $var;

    }

    echo 
    lets_learn('a'); 
    If you want to show variable_b, then change the letter a to b
    echo lets_learn('b');

  • #3
    Senior Coder
    Join Date
    Nov 2006
    Posts
    1,000
    Thanks
    0
    Thanked 0 Times in 0 Posts
    I'm not sure what you are trying to learn but try this one. :)

    PHP Code:
    <?php
    function lets_learn($b) {
        
    $a 'variable_a<br>';
        echo 
    $a;

        return (
    $b);
    }

    $b lets_learn('variable_b<br>');

    echo 
    $b;
    ?>
    david_kw

  • #4
    Regular Coder
    Join Date
    Oct 2005
    Location
    Right Here
    Posts
    654
    Thanks
    1
    Thanked 0 Times in 0 Posts
    You can return as many variables you want. Just put them in an array and return them all , then echo the one you want.

    PHP Code:
    function lets_learn(){
        
    $learn = array();
        
    $learn['a'] = 'variable_a';
        
    $learn['b'] = 'variable_b';

        return 
    $learn;
    }
    $learn lets_learn();
    echo 
    $learn['b']; 


  •  

    Posting Permissions

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