Iwonder why the out put is 0(zero) for below code snippet? Can anyone please clarify why below code output is zero.
<?php
function a($number)
{
return (b($number) * $number);
}
function b(&$number)
{
++$number;
}
echo a(5); // output 0(zero) ?
?>
You never return any value from the function, and you're trying to echo the return value.
function b(&$number)
{
return ++$number;
}
Note that this is a silly example for a function that takes its parameter by reference, since you don't have a reference to the original value 5. Something like this would be more appropriate:
function b( &$number) {
++$number;
}
$num = 5;
b( $num);
echo $num; // Prints 6
The function name is b, but you are calling a...
Also, you are echoing a function, that doesn't return a value. This means you are echoing a non-initialize variable.
You must either return a value:
return ++$number;
or echo the variable directly:
$number = 5;
b($number);
echo $number;
Related
I wonder why I am getting the result as 4
<?php
function minusNum($aNum){
$result=$aNum-1;
return $result;
}
$theNum=4;
minusNum($theNum);
echo $theNum;
?>
Your minusNum function returns a new value, it doesn't manipulate the inputted $aNum. You should use that returned value. E.g.:
$result = minusNum($theNum);
echo $result;
You need to capture the result from your function.
<?php
function minusNum($aNum){
$result = $aNum - 1;
return $result;
}
$theNum = 4;
$theNum = minusNum($theNum);
echo $theNum;
?>
Here you assign the result of the function back to your original variable $theNum.
Although you pass the variable into the function, it is only altered inside the function. The value remains the same outside of the function.
<?php
function minusNum($aNum){
$result=$aNum-1;
return $result;
}
$theNum=4;
echo minusNum($theNum);
?>
Echo the function because it returns result
but when you echo $theNum you will get the $theNum value which is 4.
Moreover the function will grape the value of any value variable that passes through not the variable it self. so you contradicting youself. I hope it helps.
Say I got some function that run some code and then return something, like this:
function something()
{
//some code
return $some[$whatever];
}
So, if I want to extract the data I generated in the function - the new value for $some, how should I do it? for example this won't do anything:
echo ($some);
Or what am I missing here, please
Since your Function returns a value, You may need to catch & store it inside a variable and then echo the variable if it is a String or do some casting to that effect. Here's an example:
<?php
function something(){
//some code
$whatever = 3;
$some = ["Peace", "Amongst", "All", "Humanity"];
return $some[$whatever];
}
$var = something();
var_dump($var); //<== DUMPS :: "Humanity"
echo $var; //<== ECHOES:: "Humanity"
Test it out here.
Cheers and Good Luck....
You are trying to return a specif key from your array, which wasn't declared. I declared an array for you, and I added the isset to check if the key is existing in the array to prevent any php warnings.
function something($findKey)
{
$some = array('key'=> 123);
if(!isset($some[$findKey])) {
return false;
}
//some code
return $some[$findKey];
}
echo something('key');
I am clearing the concept of call-by-reference.Can anyone please explain the code lines below shown as an example of call-by-reference?
<?php
function test(){
$result = 10;
return $result;
}
function reference_test(&$result){
return $result;
}
reference_test($result);
?>
You have two problems.
$result is never set and the test function is never called.
You do a pass by reference on the wrong function. A pass by reference is to change the variable inside and outside the function.
Here is the solution, changed the function a bit to show you the difference. You don't need to return the variable you changed by reference.
// Pass by ref: because you want the value of $result to change in your normal code.
// $nochange is pass by value so it will only change inside the function.
function test(&$result, $nochange){
$result = 10;
$nochange = 10;
}
// Just returns result
function reference_test($result){
return $result;
}
$result = 0; // Set value to 0
$nochange = 0;
test($result, $nochange); // $result will be 10 because you pass it by reference in this function
// $nochange wont have changed because you pass it by value.
echo reference_test($result); // echo's 10
echo reference_test($nochange); // echo's 0
I got stuck when I learned about recursive functions in PHP. I know recursive function are those which are being called by itself. My code is:
function addition_no($x,$y) {
if($x==0) {
return $x;
}
return addition_no($x+$y);
}
echo addition_no(1,2);
When I tried executing this code I get:
Warning: Missing argument 2 for addition_no(), called in
/web/com/13978781902261/main.php on line 6 and defined in
/web/com/13978781902261/main.php on line 2
What i need is to add two numbers via recursion.
I created this code in order to summarize values in an array using recursivity is:
<?php
//values to add
$add = array(5,4,4,6,7);
function addval($add,$pos) {
if($pos == 0) {
return $add[0];
}
else {
return $add[$pos] + addval($add,$pos-1);
}
}
//last position in vector
$last_position = count($add)-1;
echo addval($add, $last_position);
?>
You can try this
return addition_no($x,$y);
You have to check any condition for recursive function otherwise it will be infinite recursion..
The warning is appropriate as you call the function inside it self with a different argument structure.
Try the factorial recursive function to learn how it works:
<?php
// Initiating Recursion
echo factorial(5);
//Recursive Function Definition with 1 parameter
function factorial($number)
{
//Break condition for recursion
if($number==1)
return $number;
//Fetch and Stack Recursion
return $number*factorial($number-1);
}
So, you get the basic recursion, in simple English, as :
factorial(n) = n x factorial(n-1) = n x (n-1) x factorial(n-2)
For You particular case, you actually don't need a recursion as your arguments are not relying on the previous argument result. However, for the sake of learning, you can do something like this:
<?php
//Summation
function summation($x) {
if($x==0) {
return $x;
}
return $x+summation($x-1);
}
echo summation(5);
//Summation with 2 step
function summation($x,$y) {
if($x<1) {
return $x;
}
return $x+summation($x-$y,$y);
}
echo summation(5,2);
What does the & before the function name signify?
Does that mean that the $result is returned by reference rather than by value?
If yes then is it correct? As I remember you cannot return a reference to a local variable as it vanishes once the function exits.
function &query($sql) {
// ...
$result = mysql_query($sql);
return $result;
}
Also where does such a syntax get used in practice ?
Does that mean that the $result is returned by reference rather than by value?
Yes.
Also where does such a syntax get used in practice ?
This is more prevalent in PHP 4 scripts where objects were passed around by value by default.
To answer the second part of your question, here a place there I had to use it: Magic getters!
class FooBar {
private $properties = array();
public function &__get($name) {
return $this->properties[$name];
}
public function __set($name, $value) {
$this->properties[$name] = $value;
}
}
If I hadn't used & there, this wouldn't be possible:
$foobar = new FooBar;
$foobar->subArray = array();
$foobar->subArray['FooBar'] = 'Hallo World!';
Instead PHP would thrown an error saying something like 'cannot indirectly modify overloaded property'.
Okay, this is probably only a hack to get round some maldesign in PHP, but it's still useful.
But honestly, I can't think right now of another example. But I bet there are some rare use cases...
Does that mean that the $result is returned by reference rather than by value?
No. The difference is that it can be returned by reference. For instance:
<?php
function &a(&$c) {
return $c;
}
$c = 1;
$d = a($c);
$d++;
echo $c; //echoes 1, not 2!
To return by reference you'd have to do:
<?php
function &a(&$c) {
return $c;
}
$c = 1;
$d = &a($c);
$d++;
echo $c; //echoes 2
Also where does such a syntax get used in practice ?
In practice, you use whenever you want the caller of your function to manipulate data that is owned by the callee without telling him. This is rarely used because it's a violation of encapsulation – you could set the returned reference to any value you want; the callee won't be able to validate it.
nikic gives a great example of when this is used in practice.
<?php
// You may have wondered how a PHP function defined as below behaves:
function &config_byref()
{
static $var = "hello";
return $var;
}
// the value we get is "hello"
$byref_initial = config_byref();
// let's change the value
$byref_initial = "world";
// Let's get the value again and see
echo "Byref, new value: " . config_byref() . "\n"; // We still get "hello"
// However, let’s make a small change:
// We’ve added an ampersand to the function call as well. In this case, the function returns "world", which is the new value.
// the value we get is "hello"
$byref_initial = &config_byref();
// let's change the value
$byref_initial = "world";
// Let's get the value again and see
echo "Byref, new value: " . config_byref() . "\n"; // We now get "world"
// If you define the function without the ampersand, like follows:
// function config_byref()
// {
// static $var = "hello";
// return $var;
// }
// Then both the test cases that we had previously would return "hello", regardless of whether you put ampersand in the function call or not.