Jump to content

Replacing variable in function


dotkpay

Recommended Posts

Hello,

 

I have been trying to replace a variable's value inside a function in case it matches a certain criteria but I can't seem to get it right.

 

Let me give an example:

 

<?php

function replace_value($obj)
{
if($obj==1)
{
$obj=2;
}
}

$number = 1;
replace_value($number);

echo $number;

 

So how do I go about making $number = 2, because it still has a value of 1 even after I pas it through the function replace_value.

Link to comment
Share on other sites

The function's value it returns must be stored in a variable if you want to utilize it through the rest of your code. Otherwise you'll end up just calling the function and it won't serve any purpose since your not really storing the function's returned value anywhere.

 

What you probably want is:

 

<?php

function replace_value($obj)
{
if($obj==1)
{
$obj=2;
}

return $obj;
}

$number = 1;
$number = replace_value($number);

echo $number;

Link to comment
Share on other sites

Or you can pass the variable by reference so changes to the variable actually occur.

 

<?php

function replace_value(&$obj) // note the addition of the & before the variable, indicating it is not being passed by reference
{
if($obj==1)
{
$obj=2;
}
}

$number = 1;
replace_value($number);

echo $number;
?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.