dotkpay Posted March 31, 2012 Share Posted March 31, 2012 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. Quote Link to comment https://forums.phpfreaks.com/topic/260083-replacing-variable-in-function/ Share on other sites More sharing options...
Nasir Posted March 31, 2012 Share Posted March 31, 2012 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; Quote Link to comment https://forums.phpfreaks.com/topic/260083-replacing-variable-in-function/#findComment-1333050 Share on other sites More sharing options...
Proletarian Posted March 31, 2012 Share Posted March 31, 2012 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; ?> Quote Link to comment https://forums.phpfreaks.com/topic/260083-replacing-variable-in-function/#findComment-1333052 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.