Problem with funtion

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
php_wiz_kid
Forum Contributor
Posts: 181
Joined: Tue Jun 24, 2003 7:33 pm

Problem with funtion

Post by php_wiz_kid »

What's wrong with my function:

Code: Select all

$phone_num = '';

function empty_var($var) {
    if(empty($var)) {
        $var = 'This variable is empty<br>';
    &#125;
&#125;

empty_var($phone_num);
echo $phone_num;
It doesn't echo anything. I'm new to functions so this is probably really bad, but bear with me please.
User avatar
nielsene
DevNet Resident
Posts: 1834
Joined: Fri Aug 16, 2002 8:57 am
Location: Watertown, MA

Re: Problem with funtion

Post by nielsene »

If you want a function to change a value that was passed in you have to pass the variable by reference, instead of by value. To do this you have to add an ampersand to the function header:
php_wiz_kid wrote:What's wrong with my function:

Code: Select all

$phone_num = '';
//                         -V-  look here, add the ampersand (&)
function empty_var(&$var) {
    if(empty($var)) {
        $var = 'This variable is empty<br>';
    }
}

empty_var($phone_num);
echo $phone_num;
It doesn't echo anything. I'm new to functions so this is probably really bad, but bear with me please.
php_wiz_kid
Forum Contributor
Posts: 181
Joined: Tue Jun 24, 2003 7:33 pm

Post by php_wiz_kid »

All I had to do was enter an ampersand? Thanks alot.
Post Reply