I want to print 1 to 10 numbers using recursion but its not working.
CODE
function table($num1) {
if( $num1 <= 10 ) {
echo $num1;
echo "<br>";
table($num1++);
}
}
$num = 1;
table($num);
Here's the error
Fatal error: Maximum function nesting level of '256' reached,
aborting!
But when I am declaring $num1 as global its working fine. Please anyone tell me the reason behind it.
table($num1++) means please pass $num1 to table(), and then increase it by one. So this is not what you want.
You have to write table(++$num1) instead. It means increase $num1 first, then pass it to table().
Because you are passing a variable in copy. So the first variable has still 1 for value, and you are calling infinitely your function "table".
By default, for all variables (with the exception of objects) PHP makes a copy when passing it to a function/method. If you want to pass the same "in-memory" variable, you have to do it by reference.
$myVar=1;
myFunction($myVar);
Before, you declared your function like this:
function myFunction(&myVar) { ...}
Regards
function table($num) {
if( $num <= 10 ) {
echo $num;
echo "<br>";
table(++ $num);
}
}
$num = 1;
table($num);
table(++ $num) means increase $num first then pass to table function
Try:
function table($value) {
echo $value;
echo "<br>";
$num1=$value+1;
if($num1<=10){
table($num1);
}
}
$num = 1;
table($num);
Related
I saw this on W3Schools.
<?php
function myTest() {
static $x = 0;
echo $x;
$x++;
}
myTest();
myTest();
myTest();
?>
The output is 0, 1 and 2.
I wonder why it is not 0, 0 and 0.
Since each time the function is called, the variable x becomes 0 again.
I am a PHP beginner. Thanks!
If you declare a var static inside a function, the var keep it value over multiple calls. You could compare it to a static var inside of classes.
The code you post is a good example to see the actual effect. However I would only carefull use static inside functions, because most of the time, you need the static value somewhere else, reset the value, or something else which requires to much logic and makes the code really bad.
A good example would be a function, which returns a unique identifier for a given identifier. This could be simply achieved by using this code.
function unique_id($id) {
static $count = 0;
return $id . ($id++);
}
This example may clarify. static has a scope, thus is not a global variable. So I can define static $x outside the function and it will be defined there. Since static has scope, it wouldn't make any sense to keep on executing and resetting $x = 0. So, php will only acknowledge it the first time that line is called.
<?php
static $x = 1000;
function myTest() {
static $x = 0;
echo $x;
$x++;
}
myTest();
myTest();
myTest();
?>
I understand the use of static inside of a function.
But what I don't understand in the next example, why the variable $x can be incremented (like it was initialized to zero):
function print_conditional() {
static $x;
if($x++ == 1) {
echo "things";
} else {
echo "good ";
}
}
print_conditional();
print_conditional();
echo PHP_EOL;
This will output "good things"
So, the first time the function is called, the variable $x with no value doesn't match in the if, but the second time, look likes it was incremented to 1 and match, how is that possible?
Decrementing NULL values has no effect, but incrementing them results in 1.
Source
I have got this function in php that run and return a number. However what i want is the numbers to be add up each time the function is run.
Here is the code.
function sumRate(&$numbers) {
$sumArray="0";
if($numbers)
$sumArray=$numbers;
$countedArray=($sumArray+$numbers);
echo "<script>console.log('$countedArray')</script>";
}
example when button click Jquery Ajax sent the value to server side.
let say
sumRate("23");//console log 23
sumRate("20");//console log 20
but what I want is that each time the function is run console to log 43 instead of login each number
Weldone in advance
I'm not precisely sure of what your goal is, but if you would like to keep track of a running sum, one way is to use globals like so:
$sum = 0;
function sumRate($number) {
global $sum;
if($number) {
$sum += intval($number);
echo "<script>console.log('$sum')</script>";
}
}
sumRate("20");
sumRate("23");
Output:
<script>console.log('20')</script>
<script>console.log('43')</script>
Side note:
We cannot pass a value literal by reference. If we call sumRate("23") on a function with signature function sumRate(&$numbers), a fatal error will be thrown. Instead either pass in a variable, or omit the & from the signature.
Update:
On the client side if you would just like the final sum to be echo'd and not each number, then you can do this:
$sum = 0;
function sumRate($number) {
global $sum;
if($number) {
$sum += intval($number);
}
}
sumRate("20");
sumRate("23");
echo "<script>console.log('$sum')</script>";
Output:
<script>console.log('43')</script>
You will not see the input be added together because your input only lasts as long as the function call. You need a variable that can store this value, and is not limited to the scope of sumRate
Try
$mySum = 0;
sumRate($mySum, 23);//console log 23
sumRate($mySum, 20);//console log 43
function sumRate(&$sum, $number) {
if($number)
$sum +=$number;
echo "<script>console.log('$sum')</script>";
}
it'simple
<?php
function sumRate($numbers) {
global $countedArray;
$countedArray=$numbers+$countedArray;
return $countedArray;
}
echo sumRate(20);
echo sumRate(23);
?>
How can I auto increment a value when calling a function? Here what I'm trying to do, and I need it just this way. Cant increment it any other way except when calling the function.
function makeyogurt($type = 1) {
echo "Quantity $type.\n";
makeyogurt($type++);
}
makeyogurt();
The code you've shown will necessarily lead to an infinite loop. I guess you are searching for the static keyword:
function fun() {
static $counter = 0;
$counter++;
echo "$counter";
}
If you use static inside a function/method definition, the variable will get created only the first time the function/method is called. It's value will be saved after the call and the variable will get initialized to that value in the next call.
Now you can call the function like this:
fun();
fun();
fun();
Output will be:
1
2
3
Check this manual page
$type++ is a so called post-increment, meaning it will be incremented after the value has been passed.
What you're looking for is ++$type, which is a pre-increment and will pass the newly incremented value.
Try this:
function makeyogurt($type = 1) {
echo "Quantity $type.\n";
$type += 1;
makeyogurt($type);
}
makeyogurt();
If you don't define $type outside the function it always will be 1. I'm not exactly sure what you want, but maybe this?
$type=1;
function makeyogurt($type = 1) {
echo "Quantity $type.\n";
global $type;
++$type;
}
makeyogurt(); //makes it 2
or this:
$type=1;
function makeyogurt($a = 1) {
echo "Quantity $a.\n";
++$a;
return $a;
}
$type=makeyogurt($type); //makes it 2
I'm having trouble getting the array to work right, let me show you the code here
function scanArray(){
$al = sizeof($_userLoaders);
echo $al. "<br />";
for ($tr = 0; $tr <= $al; $tr++) {
echo "value: " .$tr. "<br />";
echo $_userLoaders[$tr];
}
}
//Fetch user's loaders.
$_userLoaders;
function get_user_loaders(){
$con = connectToMySQL();//connects to my_sql
mysql_select_db("my_database", $con);//connect database
$t = mysql_query("SELECT * FROM someTable
WHERE value_a=".$_SESSION['value_a']." AND value_b=someValue");
$x= 0;
//lets loop through the results and create an array to compare later.
while ($result = mysql_fetch_array($t)){
$_userLoaders[$x] = $result['value_c'];
$x++;
}
//lets get all the options for
print_r($_userLoaders);//this part prints what it should
scanArray();
}
okay, I minimized the code above to show you what's going on. Pretty much function get_user_loaders() works great. It fetches data from a table in a database, and returns what it should. Second, it makes an array out of it. Again, this part works great. When the print_r() method is called it prints what it should, here's an example of what it prints:
Array ( [0] => tableValue )
yes, at this point it only has one value, please note that this value can vary from no values to 100 values which is why I am using an array. In this case, i'm testing it with one value.
Now, once I call scanArray() It doesn't echo the values.
the scanArray() function echoes the following:
0
value:
so what I don't understand is why does it print it out, but it doesn't display the function? Thanks in advance.
Your problem is that $_userLoaders variable is declared outside the function and function scanArray knows nothing about it. You need to either pass that variable in as a parameter:
function scanArray($_userLoaders) {
...
}
with the call at the end being
scanArray($_userLoaders);
or alternatively declare the variable as global inside the function:
function scanArray($_userLoaders) {
global $_userLoaders;
...
}
That would be because $_userLoaders is not equal to anything inside your scanArray() function. While it's not good practice, you can add the line:
global $_userLoaders;
to your scanArray() function and every other function that uses that global variable then, and it should work.