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
https://forums.phpfreaks.com/topic/260083-replacing-variable-in-function/
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;

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;
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.